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<User> 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方法才會有值

四.源碼

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 1、配置 1.1 在project的Gradle中配置: buildscript { repositories {...
    豆漿u條閱讀 698評論 0 1
  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,881評論 18 139
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 173,099評論 25 708
  • 12月1日,一不小心就到了2017年底了,時間快得讓我害怕。 今天整理了一大堆衣物,衣柜總算是清白了點,床上也換了...
    越寫不好越要寫閱讀 261評論 0 0
  • 原型設計 愿景訴求 解決目前頁面調整交互反人類。目前頁面調整功能存在一下幾點問題: 預覽圖不能快速滾動。 預覽圖不...
    BetseyLiu閱讀 544評論 0 0