簡(jiǎn)介
GreenDAO是一個(gè)輕量、快速的ORM解決方案,它能高效地將對(duì)象映射到SQLite數(shù)據(jù)庫(kù),目前升級(jí)到了3.1版本,相較于之前的版本來(lái)說(shuō),易用性大幅度增加了,不需要一些麻煩的配置,詳情參考官方文檔 http://greenrobot.org/greendao/features/
1. 導(dǎo)入依賴
在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. 編寫需要存儲(chǔ)對(duì)象的實(shí)體類
/**
* Created by GongCheng on 2016/8/20.
* 聯(lián)系人數(shù)據(jù)庫(kù)實(shí)體類
*/
@Entity
public class Contact {
@Id
private Long id; //注意Id必須是包裝類
@NonNull
private String name;
private String number;
}
3. 編譯項(xiàng)目
直接Rebuild,發(fā)現(xiàn)生成了下面這些文件
而剛才寫的實(shí)體類也變成下面這樣
**
* Created by GongCheng on 2016/8/20.
* 聯(lián)系人數(shù)據(jù)庫(kù)實(shí)體類
*/
@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() {
}
}
這些都是通過(guò)插件生成的,不要隨意去改動(dòng)
4.初始化
初始化工作一般放在項(xiàng)目的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)系人(通過(guò)姓名)
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);
還有一些其他操作沒(méi)有一一列舉了,GreenDao也提供了對(duì)RxJava的支持