天天看點

GreenDao的使用以及一些細節的總結GreenDao

  • GreenDao
    • 一簡介
    • 一greenDao的配置
      • projectbuildgradle
      • appbuildgradle
    • 二使用
      • 配置注解映射實體類
      • 擷取DaoSession對資料進行操作
    • 細節問題
      • 凡是涉及ID的一定要使用Long類型的包裝類
      • 關聯實體的類的getset方法一定要使用Generate

GreenDao

一、簡介

GreenDao是一個對象映射資料解決方案的快速開發架構,很多sql語句直接變換簡單的代碼。

一、greenDao的配置

project/build.gradle

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.1'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
           

app/build.gradle

apply plugin: 'org.greenrobot.greendao'
android {
………………
}
dependencies {

………………
    //資料庫操作
    compile 'org.greenrobot:greendao-generator:3.2.0'
    compile 'org.greenrobot:greendao:3.2.0'
}
           

二、使用

配置注解映射實體類

greendao是插件化開發的,是以配置完注解,直接整個工程rebuild一下,就會自動生成Dao部分代碼

@Entity(nameInDb = "t_book")
public class Book {
    @Id(autoincrement = true)
    @Property(nameInDb = "id")
    private Long id;
    @Property(nameInDb = "f_book")
    private String book;
    @ToMany(referencedJoinProperty = "bookId")
    private List<Unit> units;
    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getBook() {
        return book;
    }

    public void setBook(String book) {
        this.book = book;
    }
    @Generated//一定要辨別這個@Generated,不要辨別@Keep
    public List<Unit> getUnits() {
    return units;
    }
    @Generated//一定要辨別這個@Generated,不要辨別@Keep
    public void setUnits(List<Unit> units) {
        this.units = null;
    }
}
           
@Id(autoincrement = true)
    @Property(nameInDb = "id")
    private long id;
    @Property(nameInDb = "f_book_id")
    private long bookId;//書籍id
    @ToOne(joinProperty = "bookId")//請注意:joinProperty這是變量名,不是資料庫字段
    private Book book;
    @Property(nameInDb = "f_unit")
    private String unit;//單元
    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public long getBookId() {
        return bookId;
    }

    public void setBookId(long bookId) {
        this.bookId = bookId;
    }
    @Generated(hash = )//一定要辨別這個@Generated,不要辨別@Keep
    public Book getBook() {
        return book;
    }
    @Generated//一定要辨別這個@Generated,不要辨別@Keep
    public void setBook( Book book) {
        this.book=book;
    }
           

@Entity:辨別這是一個資料庫映射類

@Id(autoincrement = true):辨別主鍵,autoincrement = true設定主鍵自增

@Property(nameInDb = “id”):辨別為資料庫字段,nameInDb = “id”表示對應資料庫的字段名。如果不使用nameInDb,将預設采用變量名作為資料庫的字段名。

@ToMany(referencedJoinProperty = “bookId”):表示一對多的關系,referencedJoinProperty = “bookId”,表示引用關聯實體的屬性“bookId”,此屬性名對應引用實體類的變量名。

@ToOne(joinProperty = “bookId”):表示一對一,或者多對一的關系,joinProperty = “bookId”,表示分享屬性“bookId”,此屬性名對應本類的變量名。

擷取DaoSession對資料進行操作

DaoMaster.DevOpenHelper mHelper =new DaoMaster.DevOpenHelper(App.getInstance(), DB_NAME, null);//DB_NAME,可以設定為已經存在的外部資料庫,如果沒有,會自動建立
SQLiteDatabase db = mHelper.getWritableDatabase();
DaoSession mDaoSession = mDaoMaster.newSession();//同步操作時,需要使用DaoSession
AsyncSession mAsyncSession= mDaoSession.startAsyncSession();//異步處理時,需要使用AsyncSession 
           

查詢資料

//直接查詢全部
UnitDao unitDao = GreenDaoHelper.getDaoSession().getUnitDao();
        unitDao.loadAll();
//根據條件查詢
UnitDao unitDao = mDaoSession .getUnitDao();
        WhereCondition eq = unitDao.Properties.Id.eq();
        WhereCondition eq5 = unitDao.Properties.BookId.eq();
        List<Unit> list = unitDao.queryBuilder().where(eq1, eq2, eq3, eq4).build().list();
           
//異步資料查詢
StudyWordScoreDao studyWordScoreDao = GreenDaoHelper.getDaoSession().getStudyWordScoreDao();
        WhereCondition eq1 = StudyWordScoreDao.Properties.BookId.eq(bookId);
        WhereCondition eq2 = StudyWordScoreDao.Properties.UnitId.eq(unitId);
        WhereCondition eq3 = StudyWordScoreDao.Properties.UnitId.eq(userId);
        WhereCondition eq4 = StudyWordScoreDao.Properties.UnitId.eq(recordId);
        Query<StudyWordScore> build = studyWordScoreDao.queryBuilder().where(eq1, eq2, eq3, eq4).build();
//        WhereCondition and = wordDao.queryBuilder().and(eq, eq1);
        asyncSession.queryList(build);
        asyncSession.setListenerMainThread(asyncOperationListener);
           

細節問題

凡是涉及ID的一定要使用Long類型的包裝類

凡是涉及ID的一定要使用Long類型的包裝類,不然,autoincrement = true會失效,我之前就是這樣,插入的資料會直接賦為“0”

//根據官網的方法,說主鍵指派為空,主鍵就會自增,但是編譯器不通過,報錯,因為初始為0,不是null,是以我就直接不設定主鍵值,果然就可以了
new Book(null,"必修一");
           

關聯實體的類的get/set方法一定要使用@Generate

//隻有使用了Generated,greenDao的插件才會将getset修改成以下代碼,如果使用@keep那就保留getset代碼,也就沒有關聯效果了
@Generated(hash = )
    public List<Unit> getUnits() {
        if (units == null) {
            final DaoSession daoSession = this.daoSession;
            if (daoSession == null) {
                throw new DaoException("Entity is detached from DAO context");
            }
            UnitDao targetDao = daoSession.getUnitDao();
            List<Unit> unitsNew = targetDao._queryBook_Units(id);
            synchronized (this) {
                if (units == null) {
                    units = unitsNew;
                }
            }
        }
        return units;
    }

    /** Resets a to-many relationship, making the next get call to query for a fresh result. */
    @Generated(hash = )
    public synchronized void resetUnits() {
        units = null;
    }
           

暫時隻總結部分,後續會繼續更新此文章