簡介
GreenDAO是一個輕量、快速的ORM解決方案逸贾,它能高效地將對象映射到SQLite數(shù)據(jù)庫,目前升級到了3.1版本,相較于之前的版本來說壁袄,易用性大幅度增加了,不需要一些麻煩的配置媚媒,詳情參考官方文檔 http://greenrobot.org/greendao/features/
1. 導入依賴
在project的build.gradle中插入:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'org.greenrobot:greendao-gradle-plugin:3.1.0'
}
}
在module的build.gradle中插入:
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'org.greenrobot:greendao-gradle-plugin:3.1.0'
}
}
2. 編寫需要存儲對象的實體類
/**
* Created by GongCheng on 2016/8/20.
* 聯(lián)系人數(shù)據(jù)庫實體類
*/
@Entity
public class Contact {
@Id
private Long id; //注意Id必須是包裝類
@NonNull
private String name;
private String number;
}
3. 編譯項目
直接Rebuild,發(fā)現(xiàn)生成了下面這些文件
而剛才寫的實體類也變成下面這樣
**
* Created by GongCheng on 2016/8/20.
* 聯(lián)系人數(shù)據(jù)庫實體類
*/
@Entity
public class Contact {
@Id
private Long id;
@NonNull
private String name;
private String number;
public String getNumber() {
return this.number;
}
public void setNumber(String number) {
this.number = number;
}
public 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;
}
@Generated(hash = 212132701)
public Contact(Long id, @NonNull String name, String number) {
this.id = id;
this.name = name;
this.number = number;
}
@Generated(hash = 672515148)
public Contact() {
}
}
這些都是通過插件生成的嗜逻,不要隨意去改動
4.初始化
初始化工作一般放在項目的Application里面執(zhí)行
/**
* Created by GongCheng on 2016/8/5.
*/
public class MainApplication extends Application {
private static MainApplication INSTANCE ;
private DaoSession daoSession;
public static MainApplication getInstance(){
return INSTANCE;
}
@Override
public void onCreate() {
super.onCreate();
INSTANCE = this;
//初始化SharedPreferences
SharedPreferencesUtils.init();
//初始化GreenDao
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this,"contacts-db");
Database db = helper.getWritableDb();
daoSession = new DaoMaster(db).newSession();
}
//得到DaoSession
public DaoSession getDaoSession() {
return daoSession;
}
}
5.正式使用
//Contact的查詢器
private Query<Contact> contactQuery;
//ContactDao
private ContactDao contactDao;
/**
* 初始化Dao
*/
private void initDao() {
//得到ContactDao
DaoSession daoSession= MainApplication.getInstance().getDaoSession();
contactDao= daoSession.getContactDao();
//查詢所有聯(lián)系人(通過姓名)
contactQuery = contactDao.queryBuilder().orderAsc(ContactDao.Properties.Name).build();
updateContacts();
}
具體操作
//查詢
List<Note> notes = notesQuery.list();
//添加
Contact contact = new Contact(null,name,number);
contactDao.insert(contact);
//刪除
contactDao.deleteByKey(contactId);
還有一些其他操作沒有一一列舉了,GreenDao也提供了對RxJava的支持