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注解
- schema:告知GreenDao當前實體屬于哪個schema
- active:標記一個實體處于活動狀態,活動實體有更新、刪除和刷新方法
- nameInDb:在數據中使用的別名,默認使用的是實體的類名
- indexes:定義索引,可以跨越多個列
- createInDb:標記創建數據庫表**
2.)基礎屬性注解
- @Id :主鍵 Long型,可以通過@Id(autoincrement = true)設置自增長
- @Property:設置一個非默認關系映射所對應的列名,默認是的使用字段名舉例:@Property (nameInDb="name")
- @NotNul:設置數據庫表當前列不能為空
- @Transient:添加次標記之后不會生成數據庫表的列
3.)索引注解
- @Index:使用@Index作為一個屬性來創建一個索引,通過name設置索引別名,也可以通過unique給索引添加約束
- @Unique:向數據庫列添加了一個唯一的約束
4.)關系注解
- @ToOne:定義與另一個實體(一個實體對象)的關系
- @ToMany:定義與多個實體對象的關系
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:
- rx.Observable<java.util.List<T>> list():獲取實體集合,返回含有該實體集合的Observable
- rx.Observable<T> unique():返回含有該實體的Observable
- rx.Observable<T> oneByOne():產生一個一個的實體
RxDao
- rx.Observable<java.lang.Long> count(): 返回一個含有數據庫數據個數的Observable。
刪除:
- rx.Observable<java.lang.Void> delete(T entity):從數據庫中刪除數據,并返回一個空的Observable
- rx.Observable<java.lang.Void> deleteAll(): 刪除所有數據,并返回一個空的Observable
- rx.Observable<java.lang.Void> deleteByKey(K key):將數據庫中主鍵為key的數據刪除,,并返回一個空的Observable
- rx.Observable<java.lang.Void> deleteByKeyInTx(java.lang.Iterable<K> keys):使用事務操作,將數據庫中,刪除key集合中每個key所對應的實體,并返回一個空的Observable
- rx.Observable<java.lang.Void> deleteByKeyInTx(K... keys): 使用事務操作,將數據庫中,刪除key[]中每個key所對應的實體,并返回一個空的Observable
- rx.Observable<java.lang.Void> deleteInTx(java.lang.Iterable<T> entities):使用事務操作,將數據庫中,刪除實體集合中每個實體所對應的實體,并返回一個空的Observable
- rx.Observable<java.lang.Void> deleteInTx(T... entities):使用事務操作,將數據庫中,刪除實體集合中每個實體[ ]所對應的實體,并返回一個空的Observable
插入:
- rx.Observable<T> insert(T entity) : 插入一個實體.
- rx.Observable<java.lang.Iterable<T>> insertInTx(java.lang.Iterable<T> entities): 插入一個list數組。
- rx.Observable<java.lang.Object[]> insertInTx(T... entities) 插入實體數組
- rx.Observable<T> insertOrReplace(T entity):插入數據,如果已存在則更新。
- rx.Observable<java.lang.Iterable<T>> insertOrReplaceInTx(java.lang.Iterable<T> entities):插入替換list數組
- rx.Observable<java.lang.Object[]> insertOrReplaceInTx(T... entities):插入替換數組
查詢,&更新:
- rx.Observable<T> load(K key):獲取主鍵為key的實體。
- rx.Observable<java.util.List<T>> loadAll():獲取全部數據。
- rx.Observable<T> refresh(T entity):更新實體。
保存:
- rx.Observable<T> save(T entity):插入數據,如果已存在則更新。
- rx.Observable<java.lang.Iterable<T>> saveInTx(java.lang.Iterable<T> entities):插入替換list數組
- rx.Observable<java.lang.Object[]> saveInTx(T... entities):插入替換數組
更新:
- rx.Observable<T> update(T entity): 跟新
- rx.Observable<java.lang.Iterable<T>> updateInTx(java.lang.Iterable<T> entities):批量更新list
- rx.Observable<java.lang.Object[]> updateInTx(T... entities):批量跟新數組。
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();
}
});