GreenDao3.0 的基本使用

来源:互联网 发布:淘宝一周可以买多少次 编辑:程序博客网 时间:2024/05/24 06:22

GreenDao是一个将对象映射到SQLite数据库中的轻量且快速的ORM解决方案。

这里只做了3.0版本基本使用的讲解,想要了解更多关于greenDAO的概念可以看官网greenDAO或者BaiDu

greenDAO 优势
1、一个精简的库
2、性能最大化
3、内存开销最小化
4、易于使用的 APIs
5、对 Android 进行高度优化
GreenDao 3.0使用
GreenDao 3.0采用注解的方式来定义实体类,通过gradle插件生成相应的代码。

下面我们来看一下基本使用
1.添加相关的依赖,及工具库,及包生成路径
1.1.首先是 app下的build.gradle

compile’org.greenrobot:greendao:3.0.1’
compile’org.greenrobot:greendao-generator:3.0.0’

apply plugin: ‘org.greenrobot.greendao’

自定义路径
greendao {
schemaVersion 1
daoPackage ‘com.anye.greendao.gen’
targetGenDir ‘src/main/java’
}

添加位置如下图:
greenDao 配置1

greenDao 配置2

1.2.工程下的:
classpath ‘org.greenrobot:greendao-gradle-plugin:3.0.0’
这里写图片描述

好了我们build一下就可以用了

2.简单的使用
我们先看使用流程,其中的细结下面会提到

2.1首先我们建一个Bean,逐一里面的注解
@Entity
public class User {
@Id
private Long id;
private String name;
@Transient
private int tempUsageCount; // not persisted
}
编译项目,User实体类会自动编译,生成get、set方法并且会在com.anye.greendao.gen目录下生成三个文件;

注意:这个bean建好了 后期修改可能出现问题
Error:Execution failed for task ‘:app:greendao’.

Constructor (see User:34) has been changed after generation.
Please either mark it with @Keep annotation instead of @Generated to keep it untouched,
or use @Generated (without hash) to allow to replace it.
错误:执行任务的应用:greendao失败。
构造函数(User类:34行)后改变了。
请添加@Keep注释@ generated保持不变,
或者使用@ generated(没有散列)允许替换它。

编译完成的bean
@Entity
public class User {

@Idprivate long id;private String name;@Transientprivate long tempUsageCount; // not persistedpublic String getName() {    return this.name;}public void setName(String name) {    this.name = name;}public long getId() {    return this.id;}public void setId(long id) {    this.id = id;}@Keep@Generated(hash = 873297011)public User(long id, String name) {    this.id = id;    this.name = name;}@Keep@Generated(hash = 586692638)public User() {}

}

2.2获得UserDao
DaoMaster.DevOpenHelper devOpenHelper = new
//notes-db 数据库名
DaoMaster.DevOpenHelper(this, “notes-db”, null);
//dao层管理
DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDatabase());

DaoSession daoSession = daoMaster.newSession();
//获得UserDao
UserDao userDao = daoSession.getUserDao();

添加一条数据
User user = new User(3,”陈xx”);

//添加数据
userDao.insert(user);

//查找数据
List userList = userDao.loadAll();
for (int i = 0; i