GreenDao3.0学习

之前项目用objectbox,现在改成greendao,记录一下自己用到的东西

导入

在build.gradle(app)下添加依赖

implementation 'org.greenrobot:greendao:3.2.2' // 添加依赖

同样在当前页面dependencies同级下添加

greendao {
    // 指定数据库schema版本号,迁移等操作会用到
    schemaVersion 3
    // 设置生成数据库文件的目录,默认是在build中,可以将生成的文件放到我们的java目录中
    targetGenDir 'src/main/java'
    // 设置生成的数据库相关文件的包名,默认为entity所在的包名
    daoPackage 'com.shufeng.greendao.gen'
}

还要在

apply plugin: 'com.android.application'下方添加
apply plugin: 'org.greenrobot.greendao' // 应用插件

在build.gradle(Project)下的dependencies下添加

// 添加插件
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'

刷新项目,然后make project,就算导入完成了

entity

 

创建对应的entity

用@entity注解

@id注解主键

@Entity
public class Catalog implements Parcelable {

    @Id(autoincrement = true)
    public Long  id;

然后builde一下,会自动生成对应的dao

DaoMaster和DaoSession都会自动生成

使用的时候可以写一个manager管理类

GreenDao3.0学习

利用daosession获取对应表的dao来使用

插入数据

Catalog  c = new Catalog ();

DataManager.getIntance.getCatalogDao().insert(c);

查询有多种方式

DataManager.getIntance.getCatalogDao().loadAll();

DataManager.getIntance.getCatalogDao().querryBuilder().list();

DataManager.getIntance.getCatalogDao().querryBuilder().where(CatalogDao.Properties.id.eq(1)).list;

删除delete

修改update

 

ToMany

根据官网文档:https://greenrobot.org/greendao/documentation/relations/

tomany有三种方式,我使用的是第一种方式

referencedJoinProperty 

@Entity
public class Father implements Parcelable {

    @Id(autoincrement = true)
    public Long  id;

    public String name;

    @ToMany(referencedJoinProperty = "myId")
    public List<Son> mySons;

//.....省略

public class Son implements Parcelable {


    @Id(autoincrement = true)
    Long id;

    private String name;

    private long myId;

}

这样就可以使用tomany

插入Son

List<Son> sonList = new ArrayList();

Son son = new Son();

sonList.add(son);

DataManager.getIntance.getSonDao().insertInTx(sonList );

插入Father

List<Father> fatherList = new ArrayList();

Father son = new Father();

fatherList .add(son);

DataManager.getIntance.getFatherDao().insertInTx(fatherList);

要将son和father联系起来

List<Son> sonList  = DataManager.getIntance.getSonDao().loadAll();

Son son = sonList.get(0);

List<Father> fatherList =  DataManager.getIntance.getFatherDao().loadAll();

Father father = fatherList.get(0);

son.setMyId(father.getId());  //根据myId来关联

DataManager.getIntance.getSonDao().updateInTx(son) //更新修改myId的son

这样要获取father的son

father.resetMySons();//清除缓存

List<Son> sons = father.getMySons();

这样就查询出来当前father的son

referencedJoinProperty 官网文档解释的意思是

参数:指定目标实体中指向该实体id的“外键”属性的名称,在本例中就是将myId作为外键指向father的Id