一.背景
之前用dbFlow,但是因?yàn)槟承┰虿贿m合所有機(jī)型,所以準(zhǔn)備用GreenDao,所以現(xiàn)在寫篇文章記錄一下使用的基本要點(diǎn)。
二.基本知識(shí)點(diǎn)和坑
- 增
mUser = new User((long)2,"anye3");
mUserDao.insert(mUser);//添加一個(gè)
- 刪
mUserDao.deleteByKey(id);
- 改
mUser = new User((long)2,"anye0803");
mUserDao.update(mUser);
- 查
List<User> users = mUserDao.loadAll();
String userName = "";
for (int i = 0; i < users.size(); i++) {
userName += users.get(i).getName()+",";
}
mContext.setText("查詢?nèi)繑?shù)據(jù)==>"+userName);
- 實(shí)體@Entity注解
schema:告知GreenDao當(dāng)前實(shí)體屬于哪個(gè)schema
active:標(biāo)記一個(gè)實(shí)體處于活動(dòng)狀態(tài),活動(dòng)實(shí)體有更新殊橙、刪除和刷新方法
nameInDb:在數(shù)據(jù)中使用的別名,默認(rèn)使用的是實(shí)體的類名
indexes:定義索引狱从,可以跨越多個(gè)列
createInDb:是否創(chuàng)建表膨蛮,默認(rèn)為true,false時(shí)不創(chuàng)建
- 基礎(chǔ)屬性注解
@Id :主鍵 Long型,可以通過(guò)@Id(autoincrement = true)設(shè)置自增長(zhǎng)
@Property:設(shè)置一個(gè)非默認(rèn)關(guān)系映射所對(duì)應(yīng)的列名季研,默認(rèn)是的使用字段名 舉例:@Property (nameInDb="name")
@NotNul:設(shè)置數(shù)據(jù)庫(kù)表當(dāng)前列不能為空
@Transient :添加次標(biāo)記之后不會(huì)生成數(shù)據(jù)庫(kù)表的列
- 索引注解
@Index:使用@Index作為一個(gè)屬性來(lái)創(chuàng)建一個(gè)索引敞葛,通過(guò)name設(shè)置索引別名,也可以通過(guò)unique給索引添加約束
@Unique:向數(shù)據(jù)庫(kù)列添加了一個(gè)唯一的約束
@OrderBy 排序
@generated 由greendao產(chǎn)生的構(gòu)造函數(shù)或方法
- 關(guān)系注解
@ToOne:定義與另一個(gè)實(shí)體(一個(gè)實(shí)體對(duì)象)的關(guān)系
@ToMany:定義與多個(gè)實(shí)體對(duì)象的關(guān)系
- 坑one
greendao的關(guān)聯(lián)關(guān)系是通過(guò)主外鍵(對(duì)象之間關(guān)聯(lián)的id)來(lái)構(gòu)建的与涡。realm是直接通過(guò)對(duì)象關(guān)系來(lái)自動(dòng)構(gòu)建的惹谐。
- 坑two
如果屬性是List<> xx, greendao不會(huì)自動(dòng)調(diào)用設(shè)置xx的值,只有手動(dòng)調(diào)用getXX的時(shí)候獲取.我在打印log的時(shí)候被坑慘了驼卖,無(wú)論怎么樣都是為null.
- 數(shù)據(jù)庫(kù)升級(jí)
如果某張表修改了字段氨肌,或者新增了一張表,必須要修改build.gradle中的schemaVersion酌畜,否則當(dāng)你升級(jí)app的時(shí)候怎囚,如果進(jìn)行了數(shù)據(jù)庫(kù)操作,會(huì)發(fā)現(xiàn)列不匹配或者表不存在等問(wèn)題桥胞,直接會(huì)導(dǎo)致app閃退恳守。但是如果僅僅是將schemaVersion加1,雖然程序不會(huì)崩潰埠戳,并且數(shù)據(jù)表的結(jié)構(gòu)也會(huì)更新成功井誉,但是之前表中的數(shù)據(jù)會(huì)全部清空。我們需要進(jìn)行手動(dòng)操作來(lái)進(jìn)行數(shù)據(jù)庫(kù)里面的數(shù)據(jù)遷移整胃,大致的思路是:創(chuàng)建臨時(shí)表(結(jié)構(gòu)與上一版本的表結(jié)構(gòu)相同)颗圣,將舊數(shù)據(jù)移到臨時(shí)表中,刪除舊版本的表,創(chuàng)建新版本的表在岂,將臨時(shí)表中的數(shù)據(jù)轉(zhuǎn)移到新表中奔则,最后再刪除臨時(shí)表。詳細(xì)方法見鏈接:
http://stackoverflow.com/a/30334668/5995409
- 自定義sql語(yǔ)句
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);
}
有的時(shí)候需要用到group by或者left join等復(fù)雜的語(yǔ)句蔽午,可以調(diào)用android原生的sqlite去進(jìn)行查詢易茬。
三.例子(oneToone,oneTomany,manyTomany)
- 一對(duì)一
一個(gè)人只有一個(gè)職業(yè)(socialRole)
我們用 @ToOne(joinProperty = "socialRoleId"),然后把SocialRole的Id設(shè)置給Person的socialRoleId就建立聯(lián)系了,不需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());
// 一般一個(gè)人就一個(gè)職業(yè)
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 關(guān)聯(lián)起來(lái)!!!!!!!!111
// 只需要關(guān)聯(lián)socialRoleId
mPerson.setSocialRoleId(mSocial.getId());
mDaoSession.getPersonDao().insertOrReplace(mPerson);
// 開始查person的里的socialRole
System.out.println("xcqw oneToone" + mPerson.getSocialRole().toString());
- 一對(duì)多
一個(gè)人寫個(gè)多篇文章
@ToMany(referencedJoinProperty = "authorId")
然后把person中的id設(shè)置給article中的authorId就建立關(guān)系了
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個(gè)篇")) {
firstArticle = true;
} else if (articleList.get(i).equals("我是第2個(gè)篇")) {
secondArticle = true;
} else {
firstArticle = false;
secondArticle = false;
}
}
}
if (!firstArticle) {
articleOne = new Article();
articleOne.setContent("我是第1個(gè)篇");
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!建立關(guān)系
articleOne.setAuthorId(mPerson.getId());
}
if (!secondArticle) {
articleTwo = new Article();
articleTwo.setContent("我是第2個(gè)篇");
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!建立關(guān)系
articleTwo.setAuthorId(mPerson.getId());
mDaoSession.getArticleDao().insertInTx(articleOne,articleTwo);
}
System.out.println("xcqw oneToMany"+mPerson.getArticleList().get(1).toString());
- 多對(duì)多
一個(gè)學(xué)生有多個(gè)老師及老,一個(gè)老師有多個(gè)學(xué)生
Student.java
@Entity
public class Student {
@Id
private Long id;
private String name;
// 對(duì)多抽莱,@JoinEntity注解:entity 中間表;sourceProperty 實(shí)體屬性骄恶;targetProperty 外鏈實(shí)體屬性
@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;
// 對(duì)多食铐,@JoinEntity注解:entity 中間表;sourceProperty 實(shí)體屬性僧鲁;targetProperty 外鏈實(shí)體屬性
@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");
// 模擬 多對(duì)多關(guān)系
//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");
注意E吧搿!寞秃!
mDaoSession.getTeacherDao().queryBuilder().list();如果在這個(gè)地方打斷點(diǎn)斟叼,下屬的students是null,只有走完兩個(gè)for循環(huán)調(diào)用get方法才會(huì)有值