转载自: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 : AreasDao.createTable(db,true ); break ; } } 三, 在Gradle面板中,运行MyDaoGenerator,为其生成新的表和操作层 运行后的结果: <img src="https://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中的两段代在码:
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; }
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的结构,你怎么应用。就和上一篇文章中的用法一样。这里就不多说了