GreenDao在Android開發中的使用
阿新 • • 發佈:2021-11-09
GreenDao和Realm對比
1.在專案的build.gradle中相應的程式碼
buildscript { dependencies { classpath "com.android.tools.build:gradle:4.2.0" //關於greendao classpath 'org.greenrobot:greendao-gradle-plugin:3.3.0' } }
2.在LibDb(注:LibDb是我的model名稱,這樣做除了方便其他地方引用外,也將關於GreenDao的程式碼從業務程式碼中解耦出來了,不建議將關於GreenDao的程式碼寫在app木蘭下。)的build.gradle中加上如下配置
plugins { id 'com.android.library' } apply plugin: 'org.greenrobot.greendao' android { greendao { //指定資料庫schema版本號,遷移等操作會用到 //新增觀測資料升級資料庫版本 <原schemaVersion 1> schemaVersion 1 //DaoSession、DaoMaster以及所有實體類的dao生成的目錄,預設為你的entity所在的包名 //daoPackage 包名 daoPackage 'com.sun.db.greendao' //這就是我們上面說到的自定義生成資料庫檔案的目錄了,可以將生成的檔案放到我們的java目錄中,而不是build中,這樣就不用額外的設定資源目錄了 //工程路徑 targetGenDir 'src/main/java' } } dependencies { //導包 api 'org.greenrobot:greendao:3.3.0' api 'org.greenrobot:greendao-generator:3.3.0' }
3.需要根據第二步中的daoPackage配置的包名創建出對應的空檔案。
4.在entity目錄下新建自己的實體類,如UserInfo
5.注意:實體類上要加上註解@Entity,主鍵id必須要並加上註解@Id(autoincrement = true) ,通過Make Project 後,我們會發現在greendao目錄下自動生成了UserInfoDao檔案。
關注下,方便檢視後期提供的相應Demo。