Android开源框架greenDAO 3.X的使用

来源:互联网 发布:淘宝网店项目策划书 编辑:程序博客网 时间:2024/06/05 22:49

前言

 greenDAO是greenrobot Open Source Libraries的一个开源框架,同时greenrobot Open Source Libraries还有一个优秀的开源框架EventBus。greenDAO是用来替代Android原始的SQLite数据库操作以便节省开发者开发成本的一款优秀的ORM(object/relational mapping)框架,将SQLite数据库的操作封装成简单的面向对象API,避免了写sql语句,同时还进行了数据库操作性能的优化。

借用官网一张图:

这里写图片描述

greenDAO框架地址:

  • github地址:https://github.com/greenrobot/greenDAO/

  • clone地址:https://github.com/greenrobot/greenDAO.git

官网:http://greenrobot.org/greendao/

文档:http://greenrobot.org/greendao/documentation/

集成greenDAO

在root build.gradle(project的build.gradle)中如下配置:

buildscript {    repositories {        jcenter()        mavenCentral() // add repository    }    dependencies {        classpath 'com.android.tools.build:gradle:2.3.1'        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2' // add plugin        // NOTE: Do not place your application dependencies here; they belong        // in the individual module build.gradle files    }}

在app build.gradle中添加:compile 'org.greenrobot:greendao:3.2.2'

apply plugin: 'org.greenrobot.greendao' // apply plugindependencies {    compile fileTree(dir: 'libs', include: ['*.jar'])    testCompile 'junit:junit:4.12'    compile 'com.android.support:appcompat-v7:23.3.0'    compile 'org.greenrobot:greendao:3.2.2' // add library}

ok,重新同步一下项目即可。

初始化greenDAO

(1) 创建实体类,如创建一个Book.java

import org.greenrobot.greendao.annotation.Entity;import org.greenrobot.greendao.annotation.Id;import org.greenrobot.greendao.annotation.Index;import org.greenrobot.greendao.annotation.NotNull;/** * Created by LT on 2017/8/19. */@Entity(indexes = {       @Index(value = "name,author DESC",unique = true)})public class Book {    @Id    private Long id;    @NotNull    private String name;    @NotNull    private String author;}

greenDAO 3使用注解进行Entity的配置,接着我们需要在Android Studio中Make Project让框架的触发器生成相关类。

Make Project后Book.java将变成:

package com.lt.greendao.entity;import android.renderscript.Sampler;import org.greenrobot.greendao.annotation.Entity;import org.greenrobot.greendao.annotation.Id;import org.greenrobot.greendao.annotation.Index;import org.greenrobot.greendao.annotation.NotNull;import org.greenrobot.greendao.annotation.Generated;/** * Created by LT on 2017/8/19. */@Entity(indexes = {       @Index(value = "name,author DESC",unique = true)})public class Book {    @Id    private Long id;    @NotNull    private String name;    @NotNull    private String author;    @Generated(hash = 423030529)    public Book(Long id, @NotNull String name, @NotNull String author) {        this.id = id;        this.name = name;        this.author = author;    }    @Generated(hash = 1839243756)    public Book() {    }    public Long getId() {        return this.id;    }    public void setId(Long id) {        this.id = id;    }    public String getName() {        return this.name;    }    public void setName(String name) {        this.name = name;    }    public String getAuthor() {        return this.author;    }    public void setAuthor(String author) {        this.author = author;    }}

同时还会在build/generated/source/…下生成BookDao,DaoMaster,DaoSession这3个类,如图:

这里写图片描述

(2)初始化greenDAO

一般我们会在我们自己的Application中初始化greenDAO,如:

package com.lt.greendao;import android.app.Application;import com.lt.greendao.entity.DaoMaster;import com.lt.greendao.entity.DaoSession;import org.greenrobot.greendao.database.Database;/** * Created by LT on 2017/8/19. */public class App extends Application {    public static final boolean ENCRYPTED = true; // 一个用于是否切换标准的数据库和加密后的数据库的标志    private DaoSession mDaoSession;    @Override    public void onCreate() {        super.onCreate();        initGreenDAO();    }    public void initGreenDAO(){        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, ENCRYPTED ? "books-db-encrypted" : "books-db");        Database db = ENCRYPTED ? helper.getEncryptedWritableDb("super-secret") : helper.getWritableDb();        mDaoSession = new DaoMaster(db).newSession();    }    public DaoSession getDaoSession() {        return mDaoSession;    }}

注意:

  1. 我们使用的是greenDAO加密的数据库,需要在App build.gradle中添加如下库,不然运行的时候会报java.lang.NoClassDefFoundError错误:

    // This is only needed if you want to use encrypted databasescompile 'net.zetetic:android-database-sqlcipher:3.5.6'
  2. 别忘了在AndroidManifest.xml中修改Application的name属性。

(3)得到Entity对应的Dao对象,然后通过这个Dao(Data Access Object)对象操作数据库,如:

// 得到BookDaoDaoSession daoSession = ((App) getApplication()).getDaoSession();mBookDao = daoSession.getBookDao();

使用greenDAO操作数据库

数据的基本操作增删改查(CRUD)

(1)添加

Book book = new Book();book.setName(name);book.setAuthor(author);mBookDao.insert(book);Log.i(TAG,"添加了一本书,id为:"+book.getId());

注意别自己设置Entity的id,greenDAO会自动生成id。

(2)删除(通过Entity的Dao对象执行deleteX()方法可以根据条件进行删除)

mBookDao.deleteAll(); // 删除所有       

(3)更新

book.setName("luotong");mBookDao.update(book);

(4)查找(还有一些系查找方法,支持原始sql查询,loadAll()…)

Query<Book> build = mBookDao.queryBuilder().build();List<Book> list = build.list();

遇到的问题

(1)问题描述

  • Error:Unable to find method ‘org.gradle.api.tasks.TaskInputs.file(Ljava/lang/Object;)Lorg/gradle/api/tasks/TaskInputFilePropertyBuilder;’.
    Possible causes for this unexpected error include:
    • Gradle’s dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)
      Re-download dependencies and sync project (requires network)
    • The state of a Gradle build process (daemon) may be corrupt. Stopping all Gradle daemons may solve this problem.
      Stop Gradle build processes (requires restart)
    • Your project may be using a third-party plugin which is not compatible with the other plugins in the project or the version of Gradle requested by the project.
    In the case of corrupt Gradle processes, you can also try closing the IDE and then killing all Java processes.

解决办法:

将project的build.gradle中的gradle的classpath替换成classpath 'com.android.tools.build:gradle:2.3.1

如:

buildscript {    repositories {        jcenter()        mavenCentral() // add repository    }    dependencies {        // classpath 'com.android.tools.build:gradle:2.0.0'        classpath 'com.android.tools.build:gradle:2.3.1'        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2' // add plugin            }}

(2)问题描述

  • A problem occurred evaluating project ‘:app’.
    java.lang.UnsupportedClassVersionError: com/android/build/gradle/AppPlugin : Unsupported major.minor version 52.0

解决办法:

Android Studio高版本需要JDK 1.8以上版本,将Android Studio的JDK版本改成1.8即可。

这里写图片描述

这里写图片描述

总结

 greenDAO号称是最快的Android ORM框架,具有许多的优点,高性能,小体积,简单易用…,可以完成大部分原生sql可以完成的操作,具体需求可以查看[官方文档](http://greenrobot.org/greendao/documentation/)及API,greenDAO还提供了RxJava的实现,同时相比2.0它使用更加简单,不再需要新建一个DaoGenerator的Java项目生成Dao,Master及Session类了 。