GreenDao基本使用
Posted dx我是大雄
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了GreenDao基本使用相关的知识,希望对你有一定的参考价值。
一.背景
之前用dbFlow,但是因为某些原因不适合所有机型,所以准备用GreenDao,所以现在写篇文章记录一下使用的基本要点。
二.基本知识点和坑
增
mUser = new User((long)2,”anye3”);
mUserDao.insert(mUser);//添加一个删
mUserDao.deleteByKey(id);改
mUser = new User((long)2,”anye0803”);
mUserDao.update(mUser);查
List users = mUserDao.loadAll();
String userName = “”;
for (int i = 0; i < users.size(); i++)
userName += users.get(i).getName()+”,”;
mContext.setText(“查询全部数据==>”+userName);实体@Entity注解
schema:告知GreenDao当前实体属于哪个schema
active:标记一个实体处于活动状态,活动实体有更新、删除和刷新方法
nameInDb:在数据中使用的别名,默认使用的是实体的类名
indexes:定义索引,可以跨越多个列
createInDb:是否创建表,默认为true,false时不创建基础属性注解
@Id :主键 Long型,可以通过@Id(autoincrement = true)设置自增长
@Property:设置一个非默认关系映射所对应的列名,默认是的使用字段名 举例:@Property (nameInDb=”name”)
@NotNul:设置数据库表当前列不能为空
@Transient :添加次标记之后不会生成数据库表的列索引注解
@Index:使用@Index作为一个属性来创建一个索引,通过name设置索引别名,也可以通过unique给索引添加约束
@Unique:向数据库列添加了一个唯一的约束
@OrderBy 排序
@generated 由greendao产生的构造函数或方法关系注解
@ToOne:定义与另一个实体(一个实体对象)的关系
@ToMany:定义与多个实体对象的关系坑one
greendao的关联关系是通过主外键(对象之间关联的id)来构建的。realm是直接通过对象关系来自动构建的。坑two
如果属性是List<> xx, greendao不会自动调用设置xx的值,只有手动调用getXX的时候获取.我在打印log的时候被坑惨了,无论怎么样都是为null.数据库升级
如果某张表修改了字段,或者新增了一张表,必须要修改build.gradle中的schemaVersion,否则当你升级app的时候,如果进行了数据库操作,会发现列不匹配或者表不存在等问题,直接会导致app闪退。但是如果仅仅是将schemaVersion加1,虽然程序不会崩溃,并且数据表的结构也会更新成功,但是之前表中的数据会全部清空。我们需要进行手动操作来进行数据库里面的数据迁移,大致的思路是:创建临时表(结构与上一版本的表结构相同),将旧数据移到临时表中,删除旧版本的表,创建新版本的表,将临时表中的数据转移到新表中,最后再删除临时表。详细方法见链接:
http://stackoverflow.com/a/30334668/5995409自定义sql语句
ChatHistoryDao dao = GreenDaoManager.getInstance().getSession().getChatHistoryDao();
Cursor cursor = dao.getDatabase().rawQuery("select t.sales_wx_nick_name,t.wx_nick_name,count(*),t.talker_id,t.sales_wx_account from chat_history t group by t.talker_id,t.sales_wx_account order by t.created_at desc", null);
while (cursor.moveToNext())
String salesWxNickName = cursor.getString(0);
String clientWxNickName = cursor.getString(1);
int chatCount = cursor.getInt(2);
int talkerId = cursor.getInt(3);
String salesWxAccount = cursor.getString(4);
有的时候需要用到group by或者left join等复杂的语句,可以调用android原生的sqlite去进行查询。
三.例子(oneToone,oneTomany,manyTomany)
- 一对一
一个人只有一个职业(socialRole)
我们用 @ToOne(joinProperty = “socialRoleId”),然后把SocialRole的Id设置给Person的socialRoleId就建立联系了,不需setSocialRole!!!!!!
Person.java
@Entity
public class Person
@Id
private Long id;
@Property(nameInDb = "address")
private String personAddress;
private Long socialRoleId;
private String name;
@ToOne(joinProperty = "socialRoleId")
private SocialRole socialRole;
@ToMany(referencedJoinProperty = "authorId")
private List<Article> articleList;
/** Used to resolve relations */
@Keep
private transient com.rebase.greendao.entity.DaoSession daoSession;
/** Used for active entity operations. */
@Keep
private transient com.rebase.greendao.entity.PersonDao myDao;
@Keep
public Person(Long id, String personAddress, Long socialRoleId, String name)
this.id = id;
this.personAddress = personAddress;
this.socialRoleId = socialRoleId;
this.name = name;
@Keep
public Person()
public Long getId()
return this.id;
public void setId(Long id)
this.id = id;
public String getPersonAddress()
return this.personAddress;
public void setPersonAddress(String personAddress)
this.personAddress = personAddress;
public Long getSocialRoleId()
return this.socialRoleId;
public void setSocialRoleId(Long socialRoleId)
this.socialRoleId = socialRoleId;
@Keep
private transient Long socialRole__resolvedKey;
/** To-one relationship, resolved on first access. */
@Keep
public SocialRole getSocialRole()
Long __key = this.socialRoleId;
if (socialRole__resolvedKey == null || !socialRole__resolvedKey.equals(__key))
final com.rebase.greendao.entity.DaoSession daoSession = this.daoSession;
if (daoSession == null)
throw new DaoException("Entity is detached from DAO context");
com.rebase.greendao.entity.SocialRoleDao targetDao = daoSession.getSocialRoleDao();
SocialRole socialRoleNew = targetDao.load(__key);
synchronized (this)
socialRole = socialRoleNew;
socialRole__resolvedKey = __key;
return socialRole;
/** called by internal mechanisms, do not call yourself. */
@Keep
public void setSocialRole(SocialRole socialRole)
synchronized (this)
this.socialRole = socialRole;
socialRoleId = socialRole == null ? null : socialRole.getId();
socialRole__resolvedKey = socialRoleId;
/**
* To-many relationship, resolved on first access (and after reset).
* Changes to to-many relations are not persisted, make changes to the target entity.
*/
@Keep
public List<Article> getArticleList()
if (articleList == null)
final com.rebase.greendao.entity.DaoSession daoSession = this.daoSession;
if (daoSession == null)
throw new DaoException("Entity is detached from DAO context");
com.rebase.greendao.entity.ArticleDao targetDao = daoSession.getArticleDao();
List<Article> articleListNew = targetDao._queryPerson_ArticleList(id);
synchronized (this)
if (articleList == null)
articleList = articleListNew;
return articleList;
/** Resets a to-many relationship, making the next get call to query for a fresh result. */
@Keep
public synchronized void resetArticleList()
articleList = null;
/**
* Convenient call for @link org.greenrobot.greendao.AbstractDao#delete(Object).
* Entity must attached to an entity context.
*/
@Keep
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.
*/
@Keep
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.
*/
@Keep
public void update()
if (myDao == null)
throw new DaoException("Entity is detached from DAO context");
myDao.update(this);
public String getName()
return this.name;
public void setName(String name)
this.name = name;
/** called by internal mechanisms, do not call yourself. */
@Keep
public void __setDaoSession(com.rebase.greendao.entity.DaoSession daoSession)
this.daoSession = daoSession;
myDao = daoSession != null ? daoSession.getPersonDao() : null;
SocialRole.java
@Entity
public class SocialRole
@Id
private Long id;
@Property(nameInDb = "job")
private String jobDesc;
private int salary;
@Generated(hash = 764507058)
public SocialRole(Long id, String jobDesc, int salary)
this.id = id;
this.jobDesc = jobDesc;
this.salary = salary;
@Generated(hash = 508250821)
public SocialRole()
public Long getId()
return this.id;
public void setId(Long id)
this.id = id;
public String getJobDesc()
return this.jobDesc;
public void setJobDesc(String jobDesc)
this.jobDesc = jobDesc;
public int getSalary()
return this.salary;
public void setSalary(int salary)
this.salary = salary;
@Override
public String toString()
return "SocialRole" +
"id=" + id +
", jobDesc='" + jobDesc + '\\'' +
", salary=" + salary +
'';
然后初始化
mPerson = mDaoSession.getPersonDao().queryBuilder().where(PersonDao.Properties.Name.eq("Jason")).unique();
if (mPerson == null)
Person person = new Person();
person.setPersonAddress("shanghai");
person.setName("Jason");
mPerson = person;
System.out.println("xcqw person"+mPerson.getName());
// 一般一个人就一个职业
mSocial = (SocialRole) mDaoSession.getSocialRoleDao().queryBuilder().unique();
if (mSocial == null)
System.out.println("xcqw mSocial == null");
SocialRole social = new SocialRole();
social.setJobDesc("法师");
social.setSalary(1000);
mDaoSession.getSocialRoleDao().insert(social);
mSocial = social;
System.out.println("xcqw social"+mSocial.getJobDesc());
// Person 跟 socialRole 关联起来!!!!!!!!111
// 只需要关联socialRoleId
mPerson.setSocialRoleId(mSocial.getId());
mDaoSession.getPersonDao().insertOrReplace(mPerson);
// 开始查person的里的socialRole
System.out.println("xcqw oneToone" + mPerson.getSocialRole().toString());
- 一对多
一个人写个多篇文章
@ToMany(referencedJoinProperty = “authorId”)
然后把person中的id设置给article中的authorId就建立关系了
Article.java
@Entity
public class Article
@Id
private Long id;
private String content;
private Long authorId;
@Generated(hash = 2128110276)
public Article(Long id, String content, Long authorId)
this.id = id;
this.content = content;
this.authorId = authorId;
@Generated(hash = 742516792)
public Article()
public Long getId()
return this.id;
public void setId(Long id)
this.id = id;
public String getContent()
return this.content;
public void setContent(String content)
this.content = content;
public Long getAuthorId()
return this.authorId;
public void setAuthorId(Long authorId)
this.authorId = authorId;
@Override
public String toString()
return "Article" +
"id=" + id +
", content='" + content + '\\'' +
", authorId=" + authorId +
'';
初始化
List<Article> articleList = mDaoSession.getArticleDao().queryBuilder().list();
if(articleList.size() >0)
for (int i = 0; i < articleList.size(); i++)
if (articleList.get(i).equals("我是第1个篇"))
firstArticle = true;
else if (articleList.get(i).equals("我是第2个篇"))
secondArticle = true;
else
firstArticle = false;
secondArticle = false;
if (!firstArticle)
articleOne = new Article();
articleOne.setContent("我是第1个篇");
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!建立关系
articleOne.setAuthorId(mPerson.getId());
if (!secondArticle)
articleTwo = new Article();
articleTwo.setContent("我是第2个篇");
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!建立关系
articleTwo.setAuthorId(mPerson.getId());
mDaoSession.getArticleDao().insertInTx(articleOne,articleTwo);
System.out.println("xcqw oneToMany"+mPerson.getArticleList().get(1).toString());
- 多对多
一个学生有多个老师,一个老师有多个学生
Student.java
@Entity
public class Student
@Id
private Long id;
private String name;
// 对多,@JoinEntity注解:entity 中间表;sourceProperty 实体属性;targetProperty 外链实体属性
@ToMany
@JoinEntity(
entity = JoinStudentToTeacher.class,
sourceProperty = "sId",
targetProperty = "tId"
)
private List<Teacher> teacherList;
/** Used to resolve relations */
@Keep
private transient com.rebase.greendao.entity.DaoSession daoSession;
/** Used for active entity operations. */
@Keep
private transient com.rebase.greendao.entity.StudentDao myDao;
@Keep
public Student(Long id, String name)
this.id = id;
this.name = name;
@Keep
public Student()
@Override
public String toString()
return "Student" +
"id=" + id +
", name='" + name + '\\'' +
", teacherList=" + teacherList +
'';
public Long getId()
return this.id;
public void setId(Long id)
this.id = id;
public String getName()
return this.name;
public void setName(String name)
this.name = name;
/**
* To-many relationship, resolved on first access (and after reset).
* Changes to to-many relations are not persisted, make changes to the target entity.
*/
@Keep
public List<Teacher> getTeacherList()
if (teacherList == null)
final com.rebase.greendao.entity.DaoSession daoSession = this.daoSession;
if (daoSession == null)
throw new DaoException("Entity is detached from DAO context");
com.rebase.greendao.entity.TeacherDao targetDao = daoSession.getTeacherDao();
List<Teacher> teacherListNew = targetDao._queryStudent_TeacherList(id);
synchronized (this)
if (teacherList == null)
teacherList = teacherListNew;
return teacherList;
/** Resets a to-many relationship, making the next get call to query for a fresh result. */
@Keep
public synchronized void resetTeacherList()
teacherList = null;
/**
* Convenient call for @link org.greenrobot.greendao.AbstractDao#delete(Object).
* Entity must attached to an entity context.
*/
@Keep
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.
*/
@Keep
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.
*/
@Keep
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. */
@Keep
public void __setDaoSession(com.rebase.greendao.entity.DaoSession daoSession)
this.daoSession = daoSession;
myDao = daoSession != null ? daoSession.getStudentDao() : null;
Teacher.java
@Entity
public class Teacher
@Id
private Long id;
private String name;
// 对多,@JoinEntity注解:entity 中间表;sourceProperty 实体属性;targetProperty 外链实体属性
@ToMany
@JoinEntity(
entity = JoinStudentToTeacher.class,
sourceProperty = "tId",
targetProperty = "sId"
)
private List<Student> studentList;
/** Used to resolve relations */
@Keep
private transient com.rebase.greendao.entity.DaoSession daoSession;
/** Used for active entity operations. */
@Keep
private transient com.rebase.greendao.entity.TeacherDao myDao;
@Keep
public Teacher(Long id, String name)
this.id = id;
this.name = name;
@Keep
public Teacher()
@Override
public String toString()
return "Teacher" +
"id=" + id +
", name='" + name + '\\'' +
", studentList=" + studentList +
'';
public Long getId()
return this.id;
public void setId(Long id)
this.id = id;
public String getName()
return this.name;
public void setName(String name)
this.name = name;
/**
* To-many relationship, resolved on first access (and after reset).
* Changes to to-many relations are not persisted, make changes to the target entity.
*/
@Keep
public List<Student> getStudentList()
if (studentList == null)
final com.rebase.greendao.entity.DaoSession daoSession = this.daoSession;
if (daoSession == null)
throw new DaoException("Entity is detached from DAO context");
com.rebase.greendao.entity.StudentDao targetDao = daoSession.getStudentDao();
List<Student> studentListNew = targetDao._queryTeacher_StudentList(id);
synchronized (this)
if (studentList == null)
studentList = studentListNew;
return studentList;
/** Resets a to-many relationship, making the next get call to query for a fresh result. */
@Keep
public synchronized void resetStudentList()
studentList = null;
/**
* Convenient call for @link org.greenrobot.greendao.AbstractDao#delete(Object).
* Entity must attached to an entity context.
*/
@Keep
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.
*/
@Keep
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.
*/
@Keep
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. */
@Keep
public void __setDaoSession(com.rebase.greendao.entity.DaoSession daoSession)
this.daoSession = daoSession;
myDao = daoSession != null ? daoSession.getTeacherDao() : null;
初始化
List<Student> studentList = mDaoSession.getStudentDao().queryBuilder().list();
if (studentList.size() == 0)
Student studentOne = new Student();
studentOne.setId(1l);
studentOne.setName("stu1");
Student studentTwo = new Student();
studentTwo.setId(2l);
studentTwo.setName("stu2");
Teacher teachOne = new Teacher();
teachOne.setId(1l);
teachOne.setName("tech1");
Teacher teachTwo = new Teacher();
teachTwo.setId(2l);
teachTwo.setName("tech2");
// 模拟 多对多关系
//Student1有teacher1 teacher2
JoinStudentToTeacher stOne = new JoinStudentToTeacher();
stOne.setSId(1l);
stOne.setTId(1l);
JoinStudentToTeacher stTwo = new JoinStudentToTeacher();
stTwo.setSId(1l);
stTwo.setTId(2l);
//teacher1 有stu1 stu2
JoinStudentToTeacher stThree = new JoinStudentToTeacher();
stThree.setSId(1l);
stThree.setTId(1l);
JoinStudentToTeacher stFour = new JoinStudentToTeacher();
stFour.setSId(2l);
stFour.setTId(1l);
mDaoSession.getJoinStudentToTeacherDao().insertOrReplaceInTx(stOne, stTwo, stThree, stFour);
mDaoSession.getStudentDao().insertOrReplaceInTx(studentOne, studentTwo);
mDaoSession.getTeacherDao().insertOrReplaceInTx(teachOne, teachTwo);
// List<Student> students = mDaoSession.getStudentDao().queryBuilder().list();
// for(int i = 0;i<students.size();i++)
// for(int j= 0;j<students.get(i).getTeacherList().size();j++)
// System.out.println("xcqw teacher i--"+i+"--j--"+j+students.get(i).getTeacherList().get(j).toString());
//
//
List<Teacher> teachers = mDaoSession.getTeacherDao().queryBuilder().list();
for(int i = 0;i<teachers.size();i++)
for(int j= 0;j<teachers.get(i).getStudentList().size();j++)
System.out.println("xcqw student i--"+i+"--j--"+j+teachers.get(i).getStudentList().get(j).toString());
System.out.println("xcqw asdsad");
注意!!!
mDaoSession.getTeacherDao().queryBuilder().list();如果在这个地方打断点,下属的students是null,只有走完两个for循环调用get方法才会有值
四.源码
以上是关于GreenDao基本使用的主要内容,如果未能解决你的问题,请参考以下文章