GreenDAO使用

GreenDAO 3.0 介绍

greenDAO是一个对象关系映射(ORM)的框架,能够提供一个接口通过操作对象的方式去操作关系型数据库
它能够让你操作数据库时更简单、更方便。如下图所示

官网地址:http://greenrobot.org/greendao/
github:https://github.com/greenrobot/greenDAO

GreenDao 优点:

  • 性能高,号称Android最快的关系型数据库
  • 内存占用小???
  • 库文件比较小,小于100K,编译时间低,而且可以避免65K方法限制
  • 支持数据库加密,greendao支持SQLCipher进行数据库加密

GreenDao 3.0最大的变化就是采用注解的方式通过编译方式生成Java数据对象和DAO对象

GreenDAO的使用方式

1.配置gradle插件

在工程的build.gradle添加如下配置:

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'org.greenrobot:greendao-gradle-plugin:3.0.0' //添加greendao用到的gradle插件
    }
}

在项目的build.gradle添加如下配置:

apply plugin: 'org.greenrobot.greendao' //应用greendao的gradle插件

...
greendao {
    schemaVersion 2 //数据库版本
    targetGenDir 'src/main/java' //生成的Dao包路径,默认路径xxx\app\build\generated\source
    daoPackage 'com.wangzhaoxia1.greendaodemo.greendao' //默认包名是程序包名
}

dependencies {
compile 'org.greenrobot:greendao:3.2.2' //添加greenDao依赖
compile 'net.zetetic:android-database-sqlcipher:3.5.7' //如果数据库需要加密,引入sqlcipher加密库
}

greendao的一些配置信息(可选):
schemaVersion:数据库schema版本,也可以理解为数据库版本号
daoPackage:设置DaoMaster 、DaoSession、Dao包名,默认包名是程序包名
targetGenDir:设置DaoMaster 、DaoSession、Dao的目录,默认路径是xxx\app\build\generated\source
targetGenDirTest:设置生成单元测试目录
generateTests:设置自动生成单元测试用例

2.新建实体
@Entity //表明这是一个GreenDao映射到数据库的实体类
public class Note {
    //Id标明主键,autoincrement可以指定是否自增,为true创建note对象就不用指定id了
    //官方文档说明类型必须为Long或long
    @Id(autoincrement = true)
    private Long id;
    @NotNull
    private String text;
    private Date date;
    private String comment;
}

GreenDao 3.0采用注解的方式生成Java数据对象和DAO对象。

此时编译一下(Build->Make Project)将自动生成DaoMaster 、DaoSession、实体对应的Dao,这些类是GreenDao框架的核心类

下面是greendao插件自动为Note类生成的构造器以及getter/setter方法

@Entity //表明这是一个GreenDao映射到数据库的实体类
public class Note {
    ...
    @Generated(hash = 1100876507)
    public Note(Long id, @NotNull String text, Date date, String comment) {
        this.id = id;
        this.text = text;
        this.date = date;
        this.comment = comment;
    }
    @Generated(hash = 1272611929)
    public Note() {
    }
    public Long getId() {
        return this.id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getText() {
        return this.text;
    }
    public void setText(String text) {
        this.text = text;
    }
    public Date getDate() {
        return this.date;
    }
    public void setDate(Date date) {
        this.date = date;
    }
    public String getComment() {
        return this.comment;
    }
    public void setComment(String comment) {
        this.comment = comment;
    }
}
3.在Application中配置DaoSession

初始化数据库和greendao核心类,这些做一次就行,比如在Application类

在App中配置DaoSession,作为数据统一操作的对象

    public class MyApplication extends Application {

        /** 是否加密标志,greendao采用SQLCipher进行数据库加密 */
        public static final boolean ENCRYPTED = false;
        /** 全局公用的DaoSession **/
        private DaoSession daoSession;

        @Override
        public void onCreate() {
            super.onCreate();

            //DevOpenHelper在升级数据库时会重建数据表,在实际项目中,如果我们需要保存旧版本的数据,
            //需要自己实现OpenHelper,把旧版本数据迁移到新版本中。
            DevOpenHelper helper = new DevOpenHelper(this, ENCRYPTED ? "notes-db-encrypted" : "notes-db");
            Database db = ENCRYPTED ? helper.getEncryptedWritableDb("super-secret") : helper.getWritableDb();
            daoSession = new DaoMaster(db).newSession();
        }

        public DaoSession getDaoSession() {
            return daoSession;
        }
    }

提醒:记得在AndroidManifest.xml中配置MyApplication.

到这里,实体类的声明、数据库操作入口都已经建立好了,接下来展示一下如何使用greendao对数据进行增删改查

4.使用greendao操作数据库

获取实体Dao,所有对数据的操作都是通过Dao执行

//获取noteDao,通过noteDao对数据进行操作
DaoSession daoSession = ((MyApplication)  getApplication()).getDaoSession();
NoteDao noteDao = daoSession.getNoteDao();
4.1 添加记录
Note note = new Note();
note.setText("这是note 内容文本");
note.setComment("这是note的comment");
note.setDate(new Date());
noteDao.insert(note);
4.2 查询记录
Query<Note> q = noteDao.queryBuilder().whereOr(
        NoteDao.Properties.Text.like("a%"),
        NoteDao.Properties.Text.like("A%")
        ).orderDesc(NoteDao.Properties.Date).build();

qb.where(Properties.FirstName.eq("Joe"),
         qb.or(Properties.YearOfBirth.gt(1970),
               qb.and(Properties.YearOfBirth.eq(1970), Properties.MonthOfBirth.ge(10))));

查询方法介绍:

4.3 删除记录

先查询,再删除

4.4 更新记录

先查询,再更新

注解

@Id 主键,可以通过@Id(autoincrement = true)设置自增长
官方文档说明主键必须使用long或Long型

Currently, entities must have a long or Long property as their primary key. This is recommended practice for Android and SQLite.

To work around this, define your key property as an additional property, but create a unique index for it:

@Id
private Long id;

@Index(unique = true)
private String key;

@Entity 用于标识这是一个需要Greendao帮我们生成代码的bean
@Transient 标识这个字段是自定义的不会创建到数据库表里

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值