当前位置: 代码迷 >> 综合 >> GreenDao之一基本使用(ToOne,ToMany都附源代码)
  详细解决方案

GreenDao之一基本使用(ToOne,ToMany都附源代码)

热度:86   发布时间:2023-10-15 09:39:41.0

   说起greendao的就要将3.0版本,3.0之前是通过java类的main方法来生成一些操作数据库的类;3.0之后是直接用注解来写实体生成对应的数据库表和操作类。我下面的字段可能写的有点随意,但是我最后都会附上源码连接,包含ToOne和ToMany的基本使用;

我写的demo代码:greenDao Demo代码,里面写的特别详细。

  以下是3.2需要导入的依赖:

compile 'org.greenrobot:greendao:3.2.0'compile 'org.greenrobot:greendao-generator:3.2.0'
greendao的官网链接: greenDao官网

   我下面会贴出3.0之前和3.0之后的greendao的一些基本用法:

   用Java类的main方法来生成相关需要的类。如下是生成1V1的外键关联代码:

 Schema schema = new Schema(1, "greendao.database");//在下面的那个路径下,生成的时候生成的包名Entity son = schema.addEntity("Son");//设置表名son.addIdProperty();son.addLongProperty("carId").primaryKey().autoincrement();//设置自增加的主键,跟上面那句代码其实是等效的son.addStringProperty("name").notNull();//设置字段不允许为nullson.addIntProperty("age");//设置一个字段来作为关联外键的时候使用Property fatherId = son.addLongProperty("fatherId").getProperty();Entity father = schema.addEntity("Father");father.addIdProperty();father.addStringProperty("name");father.addIntProperty("age");//关联外键son.addToOne(father, fatherId);try {new DaoGenerator().generateAll(schema, "greendao3/src/main/java");//在那个项目的那个文件夹下生成文件夹,文件夹的名称是new Schema的第二个参数} catch (Exception e) {e.printStackTrace();}

注意:这里面的两个路径我加了注解,您看着可能还不是很理解,您自己多试几次就懂了。

  如下是生成1V多的代码:

 Entity son1 = schema.addEntity("Son");son1.addIdProperty().primaryKey().autoincrement();son1.addStringProperty("name").notNull();son1.addIntProperty("age");Entity father1 = schema.addEntity("Father");father1.addIdProperty().primaryKey().autoincrement();father1.addStringProperty("name").notNull();father1.addIntProperty("age");Property sonId = father1.addLongProperty("sonId").getProperty();father1.addToOne(son1, sonId);son1.addToMany(father1, sonId).setName("fathers");try {new DaoGenerator().generateAll(schema, "greendao3/src/main/java");//在那个项目的那个文件夹下生成文件夹,文件夹的名称是new Schema的第二个参数} catch (Exception e) {e.printStackTrace();}

下面是用注解来生成1v1(ToOne)的代码:字段不一样请包涵一下,,,我随便从几个Demo里面扣除来的代码

@Entity(nameInDb = "son_profile")
public class Son {@Id(autoincrement = true)private Long id;@NotNull@Uniqueprivate String userName;private int age;private String address;private long fatherId;@ToOne(joinProperty = "fatherId")private Father father;/** Used to resolve relations */@Generated(hash = 2040040024)private transient DaoSession daoSession;/** Used for active entity operations. */@Generated(hash = 1926509084)private transient SonDao myDao;@Generated(hash = 1929761275)public Son(Long id, @NotNull String userName, int age, String address,long fatherId) {this.id = id;this.userName = userName;this.age = age;this.address = address;this.fatherId = fatherId;}@Generated(hash = 1259336981)public Son() {}public Long getId() {return this.id;}public void setId(Long id) {this.id = id;}public String getUserName() {return this.userName;}public void setUserName(String userName) {this.userName = userName;}public int getAge() {return this.age;}public void setAge(int age) {this.age = age;}public String getAddress() {return this.address;}public void setAddress(String address) {this.address = address;}public long getFatherId() {return this.fatherId;}public void setFatherId(long fatherId) {this.fatherId = fatherId;}@Generated(hash = 2100996716)private transient Long father__resolvedKey;/** To-one relationship, resolved on first access. */@Generated(hash = 614506380)public Father getFather() {long __key = this.fatherId;if (father__resolvedKey == null || !father__resolvedKey.equals(__key)) {final DaoSession daoSession = this.daoSession;if (daoSession == null) {throw new DaoException("Entity is detached from DAO context");}FatherDao targetDao = daoSession.getFatherDao();Father fatherNew = targetDao.load(__key);synchronized (this) {father = fatherNew;father__resolvedKey = __key;}}return father;}/** called by internal mechanisms, do not call yourself. */@Generated(hash = 1018445113)public void setFather(@NotNull Father father) {if (father == null) {throw new DaoException("To-one property 'fatherId' has not-null constraint; cannot set to-one to null");}synchronized (this) {this.father = father;fatherId = father.getId();father__resolvedKey = fatherId;}}/*** Convenient call for {@link org.greenrobot.greendao.AbstractDao#delete(Object)}.* Entity must attached to an entity context.*/@Generated(hash = 128553479)public void delete() {if (myDao == null) {throw new DaoException("Entity is detached from DAO context");}myDao.delete(this);}/*** Convenient call for {@link org.greenrobot.greendao.AbstractDao#refresh(Object)}.* Entity must attached to an entity context.*/@Generated(hash = 1942392019)public void refresh() {if (myDao == null) {throw new DaoException("Entity is detached from DAO context");}myDao.refresh(this);}/*** Convenient call for {@link org.greenrobot.greendao.AbstractDao#update(Object)}.* Entity must attached to an entity context.*/@Generated(hash = 713229351)public void update() {if (myDao == null) {throw new DaoException("Entity is detached from DAO context");}myDao.update(this);}/** called by internal mechanisms, do not call yourself. */@Generated(hash = 838735897)public void __setDaoSession(DaoSession daoSession) {this.daoSession = daoSession;myDao = daoSession != null ? daoSession.getSonDao() : null;}}

1V多(ToMany)注解生成代码:

@Entity(nameInDb = "user_profile")
public class User {@Id(autoincrement = true)private Long id;@NotNull@Uniqueprivate String userNamer;private int age;private String address;@ToMany(referencedJoinProperty = "sonId")private List<Father> fathers;/** Used to resolve relations */@Generated(hash = 2040040024)private transient DaoSession daoSession;/** Used for active entity operations. */@Generated(hash = 1507654846)private transient UserDao myDao;@Generated(hash = 1459575629)public User(Long id, @NotNull String userNamer, int age, String address) {this.id = id;this.userNamer = userNamer;this.age = age;this.address = address;}@Generated(hash = 586692638)public User() {}public Long getId() {return this.id;}public void setId(Long id) {this.id = id;}public String getUserNamer() {return this.userNamer;}public void setUserNamer(String userNamer) {this.userNamer = userNamer;}public int getAge() {return this.age;}public void setAge(int age) {this.age = age;}public String getAddress() {return this.address;}public void setAddress(String address) {this.address = address;}/*** To-many relationship, resolved on first access (and after reset).* Changes to to-many relations are not persisted, make changes to the target entity.*/@Generated(hash = 1959132710)public List<Father> getFathers() {if (fathers == null) {final DaoSession daoSession = this.daoSession;if (daoSession == null) {throw new DaoException("Entity is detached from DAO context");}FatherDao targetDao = daoSession.getFatherDao();List<Father> fathersNew = targetDao._queryUser_Fathers(id);synchronized (this) {if (fathers == null) {fathers = fathersNew;}}}return fathers;}/** Resets a to-many relationship, making the next get call to query for a fresh result. */@Generated(hash = 590801454)public synchronized void resetFathers() {fathers = null;}/*** Convenient call for {@link org.greenrobot.greendao.AbstractDao#delete(Object)}.* Entity must attached to an entity context.*/@Generated(hash = 128553479)public void delete() {if (myDao == null) {throw new DaoException("Entity is detached from DAO context");}myDao.delete(this);}/*** Convenient call for {@link org.greenrobot.greendao.AbstractDao#refresh(Object)}.* Entity must attached to an entity context.*/@Generated(hash = 1942392019)public void refresh() {if (myDao == null) {throw new DaoException("Entity is detached from DAO context");}myDao.refresh(this);}/*** Convenient call for {@link org.greenrobot.greendao.AbstractDao#update(Object)}.* Entity must attached to an entity context.*/@Generated(hash = 713229351)public void update() {if (myDao == null) {throw new DaoException("Entity is detached from DAO context");}myDao.update(this);}/** called by internal mechanisms, do not call yourself. */@Generated(hash = 2059241980)public void __setDaoSession(DaoSession daoSession) {this.daoSession = daoSession;myDao = daoSession != null ? daoSession.getUserDao() : null;}
}
这里有一个要求,就是注解ToMany的括号里面的referencedJoinProperty的sonId必须在Father表中,Father类代码如下:

@Entity(nameInDb = "father_profile")
public class Father {@Id(autoincrement = true)private Long id;@Uniqueprivate String userName;private int age;private Long sonId;@Generated(hash = 2066595481)public Father(Long id, String userName, int age, Long sonId) {this.id = id;this.userName = userName;this.age = age;this.sonId = sonId;}@Generated(hash = 383274692)public Father() {}public Long getId() {return this.id;}public void setId(Long id) {this.id = id;}public String getUserName() {return this.userName;}public void setUserName(String userName) {this.userName = userName;}public int getAge() {return this.age;}public void setAge(int age) {this.age = age;}public Long getSonId() {return this.sonId;}public void setSonId(Long sonId) {this.sonId = sonId;}}

 下面是一些调用代码,3.0前后的增删改查代码都基本一样: 

 先要初始化,我选择在DbManager里面来进行初始化,然后在application里面来初始化一下就可以了。

public class DbManager {private UserDao mUserDao;private FatherDao mFatherDao;private DbManager() {}private static final class Holder {private static final DbManager INSTANCE = new DbManager();}public static DbManager getInstance() {return Holder.INSTANCE;}public DbManager init(Context context) {initDao(context);return this;}private void initDao(Context context) {final DaoMaster.OpenHelper helper = new DaoMaster.DevOpenHelper(context, "person.db");final Database db = helper.getWritableDb();DaoSession mDaoSession = new DaoMaster(db).newSession();mUserDao = mDaoSession.getUserDao();mFatherDao = mDaoSession.getFatherDao();}public UserDao getUserDao() {return mUserDao;}public FatherDao getFatherDao() {return mFatherDao;}
}
在application里面初始化:

public class App extends Application {public static Context shareInstance;@Overridepublic void onCreate() {super.onCreate();shareInstance = this;DbManager.getInstance().init(shareInstance);}
}