GreenDao 使用介绍

地址
  1. http://greenrobot.org/greendao/
  2. https://github.com/greenrobot/greenDAO
项目环境配置

在工程的根目录的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
    }
}

modulebuild.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.**
简单使用介绍
  1. 定义数据库版本以及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'
    }

    这个配置不是必须的。

  2. 实体类和注解。
    1. @Entity 关于实体的参数配置,一般默认参数即可,详细配置请自行参考源码注释
    2. 其他常用注解
      1. @Id 主键(需要注意的地方,注解只能工作在Long或者long属性)
      2. @Property 可选 指定列名
      3. @Transient 也可以使用Java关键字transient 该属性不会被持久化
      4. @NotNull 等同于数据表属性添加NOT NULL
      5. @Unique 同上
      6. @Index 索引
  3. 在定义好实体类以后需要进行一步操作Make Project,会在targetGenDir目录下面生成DaoMasterDaoSessionxxDao
  4. 初始化数据库相关

         // 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获取

  5. 数据表操作


    前三个都很简单,自行查看API
    最后一个查找数据比较麻烦,

    最简单的查找

    public T load(K key) // 根据主键查找
    public List<T> loadAll() // 加载所有可用数据
    public T loadByRowId(long rowId) // 根据rowid查找,rowid请自行参阅数据库知识

    QueryBuilder可以实现各种查找,这个地方需要说明一下,他要配合在targetGenDir目录下面的xxDao里面的Properties(静态内部类)一起使用。Properties里面就是若干个Property(静态常量)。所以具体的操作直接查看Property类即可

其他说明
  1. 如果要是用SQLCipher进行数据加密,需要在modulebuild.gradle里面添加

    compile 'net.zetetic:android-database-sqlcipher:3.5.7@aar'
  2. 如果使用Rx,需要在modulebuild.gradle里面添加

    compile 'io.reactivex:rxandroid:1.2.1'
    compile 'io.reactivex:rxjava:1.2.9'

稍后会整理一份代码提供下载参阅,不要错过哦
梯云纵

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值