Android数据库框架GreenDao的简单使用

1.引入greendao

首先在project的gradle文件中引入greenDAO插件:

 classpath 'org.greenrobot:greendao-gradle-plugin:3.1.0' 

然后在module的gradle文件中添加greenDAO的插件,并引入相关类库:

apply plugin: 'org.greenrobot.greendao' 

  1. greendao{  
  2.         schemaVersion 1  
  3.         targetGenDir 'src/main/java'  
  4.     }  

 compile 'org.greenrobot:greendao:3.1.0'  

2.数据库初始化:

数据库引入成功后,在使用之前,我们还得先来创建一个实体类:

@Entity
public class User {
    @Id
    private Long id;
    @Property(nameInDb = "USERNAME")
    private String username;
    @Property(nameInDb = "NICKNAME")
    private String nickname;
}  
数据库初始化:


DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(getApplicationContext(), "lenve.db", null);
DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDb());

DaoSession daoSession = daoMaster.newSession();

想要操作User实体类,得先有一个UserDao:

userDao = daoSession.getUserDao();

3.添加数据:

User user = new User(null, "zhangsan" + random.nextInt(9999),"张三");  
    userDao.insert(user);  
4.删除数据:

List userList = (List) userDao.queryBuilder().where(UserDao.Properties.Id.le(10)).build().list();  
    for (User user : userList) {
            userDao.delete(user);
            } 
5.修改数据:
User user = userDao.queryBuilder()
        .where(UserDao.Properties.Id.ge(10), UserDao.Properties.Username.like("%90%")).build().unique();  
    if (user == null) {
            Toast.makeText(MainActivity.this, "用户不存在!", Toast.LENGTH_SHORT).show();
            }else{
            user.setUsername("王五");
            userDao.update(user);
            }

6.查询数据:

List list = userDao.queryBuilder()
        .where(UserDao.Properties.Id.between(2, 13)).limit(5).build().list();  
    for (int i = 0; i < list.size(); i++) {
    Log.d("google_lenve", "search: " + list.get(i).toString());
    }   
OK,这就是greenDAO数据库框架的一个简单介绍


你可能感兴趣的:(Android数据库框架GreenDao的简单使用)