GreenDao3.x 的Rx的使用

2017-07-31  本文已影响922人  johnnycmj

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


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

1 greendao-gradle-plugin 配置

在根build.gradle 中的buildscript 的dependencies 配置 :classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'

buildscript {
    repositories {
        jcenter()
        mavenCentral()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.2'
        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'
    }
}

2 加apply plugin

在组件build.gradle 头部中加入apply plugin: 'org.greenrobot.greendao'

apply plugin: 'org.greenrobot.greendao'

3 数据库版本

greendao {
    schemaVersion 1
}

4 依赖配置


    compile 'org.greenrobot:greendao:3.2.2'
    // This is only needed if you want to use encrypted databases
    compile 'net.zetetic:android-database-sqlcipher:3.5.6'

    compile 'com.jakewharton.rxbinding:rxbinding:1.0.1'
    compile 'io.reactivex:rxandroid:1.2.1'
    compile 'io.reactivex:rxjava:1.2.9'

5 新建实体

/**
 * <pre>
 *     author: chmj
 *     time  : 2017/7/28
 *     desc  :
 * </pre>
 */

/**
 * schema:告知GreenDao当前实体属于哪个schema
 * active:标记一个实体处于活动状态,活动实体有更新、删除和刷新方法
 * nameInDb:在数据中使用的别名,默认使用的是实体的类名
 * indexes:定义索引,可以跨越多个列
 * createInDb:标记创建数据库表
 */
@Entity
public class Student {

    /**
     * @Id :主键 Long型,可以通过@Id(autoincrement = true)设置自增长
     * @Property 设置一个非默认关系映射所对应的列名,默认是的使用字段名 举例:@Property (nameInDb="name")
     * @NotNul 设置数据库表当前列不能为空
     * @Transient 添加次标记之后不会生成数据库表的列
     * @Index 使用@Index作为一个属性来创建一个索引,通过name设置索引别名,也可以通过unique给索引添加约束
     * @Unique 向数据库列添加了一个唯一的约束
     * @ToOne 定义与另一个实体(一个实体对象)的关系
     * @ToMany 定义与多个实体对象的关系
     */
    @Id(autoincrement = true)
    private Long id;

    private String studentName;

    private int age;

    private Date birthday;


    @Generated(hash = 65138557)
    public Student(Long id, String studentName, int age, Date birthday) {
        this.id = id;
        this.studentName = studentName;
        this.age = age;
        this.birthday = birthday;
    }

    @Generated(hash = 1556870573)
    public Student() {
    }


    public String getStudentName() {
        return studentName;
    }

    public void setStudentName(String studentName) {
        this.studentName = studentName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", studentName='" + studentName + '\'' +
                ", age=" + age +
                ", birthday=" + TimeUtils.date2String(birthday) +
                '}';
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }
}

1.)实体@Entity注解

2.)基础属性注解

3.)索引注解

4.)关系注解

6 编译

点击编译,则会自动创建代码,目录在:build ->generated -> source -> greendao

会自动创建: DaoMaster,DaoSession, Dao;

7 DbHelper


/**
 * <pre>
 *     author: chmj
 *     time  : 2017/7/27
 *     desc  :
 * </pre>
 */

public class DbHelper {

    /** 数据库是否加密的标识 */
    public static final boolean ENCRYPTED = true;

    private DaoSession mDaoSession;

    private DbHelper() {
        createDao();
    }

    private static class SingletonHolder {
        private static final DbHelper INSTANCE = new DbHelper();
    }

    //获取单例
    public static DbHelper getInstance() {
        return DbHelper.SingletonHolder.INSTANCE;
    }


    public DaoSession getDaoSession() {
        return mDaoSession;
    }

    private void createDao(){
        //创建数据库
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(Utils.getContext(), ENCRYPTED ? "notes-db-encrypted" : "notes-db");
        //获取数据库读写的权限,如果进行加密调用helper.getEncryptedWritableDb("super-secret"),参数为设置的密码
        Database db = ENCRYPTED ? helper.getEncryptedWritableDb("super-secret") : helper.getWritableDb();
        mDaoSession = new DaoMaster(db).newSession();
    }
}

如果数据是加密的,则要用解密去获取实例。

8 初始化

在Application 或者需用到的Activity的onCreate()中初始化。

        
        DaoSession daoSession = DbHelper.getInstance().getDaoSession();
        noteDao = daoSession.getStudentDao().rx();
        noteRxQuery = daoSession.getStudentDao().queryBuilder().orderAsc(StudentDao.Properties.StudentName).rx();

查询noteRxQuery.list()

noteRxQuery.list()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<List<Student>>() {
                    @Override
                    public void call(List<Student> students) {
                        mAdapter.setData(students);
                        mSwipeLayout.setRefreshing(false);
                    }
                });

RxQuery:

RxDao

删除:

插入:

查询,&更新:

保存:

更新:

noteDao.insert(student)
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<Student>() {
                    @Override
                    public void call(Student student) {
                        mAddDailog.cancel();
                        onRefresh();
                    }
                });
noteDao.update(mUpdateStu)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Action1<Student>() {
                            @Override
                            public void call(Student student) {
                                mEditDialog.cancel();
                                onRefresh();
                            }
                        });
noteDao.delete(mDelStu)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Action1<Void>() {
                            @Override
                            public void call(Void aVoid) {
                                mDelDialog.cancel();
                                onRefresh();
                            }
                        });
上一篇下一篇

猜你喜欢

热点阅读