GreenDao是一款Android上的ORM框架(对象/关系映射),在数据库开发中能帮我们从枯燥的CRUD中节约大量的时间,这里针对GreenDao3.0以后的版本做一个简单的使用介绍。
1、引入
GreenDao Github地址
引入Gradle插件,
在根目录的build.gradle
中,加入GreenDao的插件依赖地址:
dependencies {
classpath 'com.android.tools.build:gradle:3.4.3'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "com.jakewharton:butterknife-gradle-plugin:10.2.1"
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2' // greendao 插件依赖
}
在包含entity注解的实体类所在module的build.gradle
中,加入使用插件:
apply plugin: 'org.greenrobot.greendao'
在base module或者你的数据库管理类所在的module的build.gradle
中加入基本依赖:
api 'org.greenrobot:greendao:3.2.2'
GreenDao的基本配置:
greendao {
//数据库的schema版本,也可以理解为数据库版本号,如果版本升级,数据库表字段发生变化,必须要升级
schemaVersion 1
//设置DaoMaster、DaoSession、Dao包名,也就是要放置这些类的包的全路径。可以不设置,使用默认值
daoPackage 'tsou.com.simple.greendaoforkotlin.greendao'
//设置DaoMaster、DaoSession、Dao目录 , 可以不设置,使用默认值
targetGenDir 'src/main/java'
}
如果使用混淆,那么需要加入以下配置:
-keepclassmembers class * extends org.greenrobot.greendao.AbstractDao {
public static java.lang.String TABLENAME;
}
-keep class **$Properties { *; }
# If you DO use SQLCipher:
-keep class org.greenrobot.greendao.database.SqlCipherEncryptedHelper { *; }
# If you do NOT use SQLCipher:
-dontwarn net.sqlcipher.database.**
# If you do NOT use RxJava:
-dontwarn rx.**
这里引入的是3.2.2版本,这里提一句api
和implementation
区别只是影响编译期的依赖传递,我是在base模块引入的,为了让应用模块都能正常使用,所以使用的是api
来引入。
上述依赖都添加完成之后,写一个作为表的entity的case:
@Entity
public class Chapter {
public Chapter(String name) {
this.name = name;
}
/*