前言
GreenDao 优点:
性能高,号称Android最快的关系型数据库
- 内存占用小
- 库文件比较小,小于100K,编译时间低,而且可以避免65K方法限制
- 支持数据库加密 greendao支持SQLCipher进行数据库加密
- 简洁易用的API
本文通过示例演示GreenDao的使用步骤,旨在通过本文对GreenDao使用有个认识
Part1:配置说明
Step1:project的build.gradle
在dependencies节点下添加classpath
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.1'
注意仓库是mavenCentral()
如repositories节点下没有mavenCentral(),则需要手动添加
![](https://img.haomeiwen.com/i2804698/35039f97da4db53b.png)
Step2:module的build.gradle
android节点下添加如下
![](https://img.haomeiwen.com/i2804698/74b6ca55d39f2945.png)
最顶部添加
apply plugin: 'org.greenrobot.greendao'
dependencies节点下添加
compile 'org.greenrobot:greendao:3.2.0'
Step3:添加权限
![](https://img.haomeiwen.com/i2804698/7161f5c2e6c92e39.png)
Part2:实做部分
Step1:建立Orm关系,以Student 为例。
注意这里需要添加@Entity并导入import org.greenrobot.greendao.annotation.Entity;
构造函数前添加@Generated并导入import org.greenrobot.greendao.annotation.Generated;
private long id;前面添加@Id并导入import org.greenrobot.greendao.annotation.Id;否则在根据id删除指定数据时会报类型不匹配的错
![](https://img.haomeiwen.com/i2804698/1fc487648cbca554.png)
Step2:Rebuild工程,在daoPackage 下生成DaoMaster、DaoSession、StudentDao三个类。
![](https://img.haomeiwen.com/i2804698/a5c335457d86ac97.png)
Step3:通过DaoMaster获取Session对象。
mDaoSession=mDaoMaster.newSession();再通过DaoSession.getDao()即可拿到StudentDao对象。
初始化数据库
![](https://img.haomeiwen.com/i2804698/e1118212e9e70a51.png)
![](https://img.haomeiwen.com/i2804698/8789eced3e597f3a.png)
添加学生数据
![](https://img.haomeiwen.com/i2804698/eb9a6f8295a7a44b.png)
通过id删除学生数据
![](https://img.haomeiwen.com/i2804698/6688c6c8f65e8856.png)
通过id查询学生数据
![](https://img.haomeiwen.com/i2804698/ab75c3c84bbec186.png)
Step4:使用Dao层进行增删改查。
最后说明:GreenDao的特色是插件生成Dao类,因此必须配置正确,而数据库版本,表名等配置为自动生成,由greendao来维护。
网友评论