地址
项目环境配置
在工程的根目录的build.gradle中配置
buildscript {
repositories {
jcenter()
mavenCentral() // add repository
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.3'
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2' // add plugin
}
}
在module的build.gradle中配置
apply plugin: 'org.greenrobot.greendao' // apply plugin
dependencies {
compile 'org.greenrobot:greendao:3.2.2' // add library
}
然后同步一下工程
混淆
-keepclassmembers class * extends org.greenrobot.greendao.AbstractDao {
public static java.lang.String TABLENAME;
}
-keep class **$Properties
如果你没有使用SQLCipher,还需要添加如下配置,作用不输出相关警告
-dontwarn org.greenrobot.greendao.database.**
如果你没有使用Rx,还需要添加如下配置,作用不输出相关警告
-dontwarn rx.**
简单使用介绍
定义数据库版本以及Dao的相关设置,在根目录的build.gradle添加配置
greendao { //数据库schema版本 schemaVersion 1 //设置DaoMaster DaoSession Dao包名,默认的是bean所在的包名 daoPackage 'com.xxx.xxx.greendao' //设置DaoMaster DaoSeeeion Dao目录,默认是build/generated/source/greendao //targetGenDir 'src/main/greendao' //设置true,自动生成测试单元 //generateTests 'true' //设置生成的单元测试目录,默认是src/androidTest/java //targetGenDirTests 'src/androidTest/java' }
这个配置不是必须的。
- 实体类和注解。
- @Entity 关于实体的参数配置,一般默认参数即可,详细配置请自行参考源码注释
- 其他常用注解
- @Id 主键(需要注意的地方,注解只能工作在Long或者long属性)
- @Property 可选 指定列名
- @Transient 也可以使用Java关键字transient 该属性不会被持久化
- @NotNull 等同于数据表属性添加NOT NULL
- @Unique 同上
- @Index 索引
- 在定义好实体类以后需要进行一步操作Make Project,会在targetGenDir目录下面生成DaoMaster,DaoSession,xxDao
初始化数据库相关
// SQLiteOpenHelper 最底层的实现 DaoMaster.DevOpenHelper openHelper = new DaoMaster.DevOpenHelper(this, "green-dao-db"); //openHelper.getWritableDatabase(); // 这个很简单 Database db = openHelper.getEncryptedWritableDb("password-123456"); // 重点说明这个 对数据库进行加密 SQLCipher mDaoSession = new DaoMaster(db).newSession();
具体的实体Dao,通过DaoSession获取
数据表操作增,删,改,查
前三个都很简单,自行查看API
最后一个查找数据比较麻烦,最简单的查找
public T load(K key) // 根据主键查找 public List<T> loadAll() // 加载所有可用数据 public T loadByRowId(long rowId) // 根据rowid查找,rowid请自行参阅数据库知识
QueryBuilder可以实现各种查找,这个地方需要说明一下,他要配合在targetGenDir目录下面的xxDao里面的Properties(静态内部类)一起使用。Properties里面就是若干个Property(静态常量)。所以具体的操作直接查看Property类即可
其他说明
如果要是用SQLCipher进行数据加密,需要在module的build.gradle里面添加
compile 'net.zetetic:android-database-sqlcipher:3.5.7@aar'
如果使用Rx,需要在module的build.gradle里面添加
compile 'io.reactivex:rxandroid:1.2.1' compile 'io.reactivex:rxjava:1.2.9'
稍后会整理一份代码提供下载参阅,不要错过哦
梯云纵