GreenDao的簡單使用說明(四)特殊的單表1:n
來自: http://blog.csdn.net//chenguang79/article/details/50467383
我們在做系統的時候,有時間會遇到單表自循環的情況,最常見的就是省市信息表,它們通過parentid來確定父子關系,這就是一種比較特殊的1:n的關系,我們來看一下,在GreenDao中是如何實現的。
一,我們先要MyDaoGenerator.java中添加這個新的bean
Entity areaBean = schema.addEntity("Areas");
areaBean.implementsSerializable();
areaBean.addIdProperty();
areaBean.addStringProperty("areaName");
Property parentId = areaBean.addLongProperty("parentId").getProperty();
areaBean.addToOne(areaBean,parentId).setName("parent");
areaBean.addToMany(areaBean,parentId).setName("children"); 看到了吧,就是自己和自己相連,即是1,又是n
別忘了,修改上面的Schema schema = new Schema(4, "greendao"); 告訴系統,我們升級了,有新表進來。
二,修改THDevOpenHelper.java,我們繼承的這個類
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
switch (oldVersion) {
case 4:
//創建新表,注意createTable()是靜態方法
//infosDao.createTable(db, true);
//infoTypeDao.createTable(db,true);
AreasDao.createTable(db,true);
// 加入新字段
// db.execSQL("ALTER TABLE 'moments' ADD 'audio_path' TEXT;");
// TODO
break;
}
}
三, 在Gradle面板中,運行MyDaoGenerator,為其生成新的表和操作層
運行后的結果:
<img src="http://img.blog.csdn.net/20160106111447135?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" /> 幫我們生成了相應了Areas.java和AreasDao.java兩個類,我們來看一下,Areas.java中的兩段代在碼:
/** To-one relationship, resolved on first access. */
public Areas getParent() {
Long __key = this.parentId;
if (parent__resolvedKey == null || !parent__resolvedKey.equals(__key)) {
if (daoSession == null) {
throw new DaoException("Entity is detached from DAO context");
}
AreasDao targetDao = daoSession.getAreasDao();
Areas parentNew = targetDao.load(__key);
synchronized (this) {
parent = parentNew;
parent__resolvedKey = __key;
}
}
return parent;
} /** To-many relationship, resolved on first access (and after reset). Changes to to-many relations are not persisted, make changes to the target entity. */
public List<Areas> getChildren() {
if (children == null) {
if (daoSession == null) {
throw new DaoException("Entity is detached from DAO context");
}
AreasDao targetDao = daoSession.getAreasDao();
List<Areas> childrenNew = targetDao._queryAreas_Children(id);
synchronized (this) {
if(children == null) {
children = childrenNew;
}
}
}
return children;
} 這兩段代碼,我不說,大家也知道是干什么用的了。就這么簡單,我們就實現了單表1:n的結構,你怎么應用。就和上一篇文章中的用法一樣。這里就不多說了
本文由用戶 ChongAsbury 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!