- gradle添加依賴
```groovy
// In your root build.gradle file:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.1'
classpath 'org.greenrobot:greendao-gradle-plugin:3.1.0' // add plugin
}
}
// In your app projects build.gradle file:
apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao' // apply plugin
dependencies {
compile 'org.greenrobot:greendao:3.2.2' // add library
}
- 配置Module根目錄下的build.gradle文件
android {
......
// 數(shù)據(jù)庫(kù)的版本及Dao相關(guān)設(shè)置
greendao {
// 數(shù)據(jù)庫(kù)schema版本馅笙,也可以理解為數(shù)據(jù)庫(kù)版本號(hào)
schemaVersion 1000
// 設(shè)置DaoMaster 伦乔、DaoSession、Dao包名
daoPackage 'com.mazaiting.greendaotest.db.dao'
// 設(shè)置DaoMaster 延蟹、DaoSession评矩、Dao目錄
targetGenDir 'src/main/java'
// 設(shè)置自動(dòng)生成單元測(cè)試用例
generateTests
}
}
- 新建實(shí)體類(lèi)
package com.mazaiting.greendaotest.db.entry;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Id;
/**
* Created by mazaiting on 2017/9/7.
*/
@Entity
public class NewFriend {
// 設(shè)置自增長(zhǎng),不能設(shè)置為int
@Id(autoincrement = true)
private long id;
private String name;
private int age;
}
- 重新編譯工程(build->Rebuild Project)。
編譯完成后,在com.mazaiting.greendaotest.db.dao下生成如下文件:
測(cè)試1.png
- 使用GreenDao添加數(shù)據(jù)
/**
* 使用GreenDao
*/
private void userGreenDao() {
DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(this, "test.db");
DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDb());
DaoSession daoSession = daoMaster.newSession();
NewFriend newFriend = new NewFriend();
newFriend.setName("mazaiting");
newFriend.setAge(22);
daoSession.insert(newFriend);
}
運(yùn)行后阱飘,在"/data/data/com.mazaiting.greendaotest/databases/"路徑下生成test.db數(shù)據(jù)庫(kù),庫(kù)中生成相對(duì)應(yīng)的實(shí)體表名(NEW_FRIEND),并將數(shù)據(jù)插入了其中虱颗。
結(jié)果.png
- 工具類(lèi)
package com.mazaiting.greendaotest.db.dao;
import android.content.Context;
/**
* Created by mazaiting on 2017/9/7.
*/
public class DbManager {
private static final String DB_NAME = "test.db";
private static DbManager mDbManager = null;
private static DaoSession mDaoSession = null;
private DbManager(Context context){
DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(context, DB_NAME);
DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDb());
mDaoSession = daoMaster.newSession();
// 在控制臺(tái)打印出sql語(yǔ)句和查詢的值
QueryBuilder.LOG_SQL = true;
QueryBuilder.LOG_VALUES = true;
}
public static DbManager getInstance(Context context){
if (null == mDbManager){
synchronized (DbManager.class){
if (null == mDbManager){
mDbManager = new DbManager(context);
}
}
}
return mDbManager;
}
public NewFriendDao getNewFriendDao(){
return mDaoSession.getNewFriendDao();
}
}