1.配置 root的build.gradle
buildscript {
repositories {
jcenter()
...
mavenCentral() // 添加倉庫
}
dependencies {
...
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2' // 添加插件
}
}
2.配置module的build.gradle
apply plugin: 'org.greenrobot.greendao' // 在最上方添加插件
dependencies {
...
implementation 'org.greenrobot:greendao:3.2.2' // 添加庫
}
3.繼續(xù)配置module的build.gradle(添加schema版本)
android {
...
}
greendao {
schemaVersion 2
daoPackage 'xxx.xxx.xx.greendao'
targetGenDir 'src/main/java'
}
dependencies {
...
}
- schemaVersion
數(shù)據(jù)庫schema版本(必填,數(shù)據(jù)庫版本升級時(shí)需要增加版本號)
- daoPackage
設(shè)置(自動生成類)DAOs, DaoMaster, and DaoSession的包名
- targetGenDir
設(shè)置(自動生成類)DAOs, DaoMaster, and DaoSession的目錄
4.創(chuàng)建實(shí)體類
@Entity
public class User {
@Id(autoincrement = true)
private Long id;
private String name;
}
- 通過@ Entity設(shè)置實(shí)體類
- @Id 主鍵(必須是Long型)可以通過(autoincrement = true)設(shè)置為主鍵自增長
- @NotNull 設(shè)置當(dāng)前列不能為空
5.Application中進(jìn)行初始化
// 在onCreate()進(jìn)行初始化
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "notes.db", null);
Database db = helper.getWritableDb();
DaoMaster daoMaster = new DaoMaster(db);
daoSession = daoMaster.newSession();
// 提供獲得DaoSession對象的方法
public DaoSession getDaoSession() {
return daoSession;
}
6.在activities/fragments獲得DAO進(jìn)行操作數(shù)據(jù)庫
getDaoSession().getNoteDao()材失;
7.刪除數(shù)據(jù)庫所有數(shù)據(jù)
// 項(xiàng)目中如果登錄用戶進(jìn)行變更數(shù)據(jù)不能共用氛琢,則需要刪除表并創(chuàng)建表
// getDb()為Application中提供獲得Database的方法
DaoMaster.dropAllTables(getDb(),true);
DaoMaster.createAllTables(getDb(),true);
8.表關(guān)聯(lián)
比如:一個(gè)組長有多個(gè)組員(一對多關(guān)系)
/**組長表*/
@Entity
public class Leader {
@Id(autoincrement = true)
private Long id;
private LeaderName;
@ToMany(referencedJoinProperty = "memberId")
private List<Member> list;
}
/**組員表*/
@Entity
public class Member {
@Id(autoincrement = true)
private Long id;
// 此處自定義memberId,用于和組長對應(yīng)
private Long memberId;
private String memberName;
}
json數(shù)據(jù)
{
"leaderName": "劉xx",
"members": [
{
"jyzyxm": "焦xx"
},
{
"jyzyxm": "王xx"
}
]
}
存數(shù)據(jù)
leader = new Leader("劉xx")掏熬;
leaderDao.insert(leader);
for (int k = 0; k < members.size(); k++) {
membersDao.insert(new Member(memberName, leader.getId()));
}
9.使用外部數(shù)據(jù)庫
所謂外部數(shù)據(jù)庫文件此處指的就是一個(gè)在外部單獨(dú)創(chuàng)建的db文件搀崭,假設(shè)有這么一個(gè)場景叨粘,項(xiàng)目中有一些本地?cái)?shù)據(jù),不需要接口去獲取的(不需要進(jìn)行網(wǎng)絡(luò)操作)门坷,比如全國各個(gè)省各個(gè)市的一些基本信息宣鄙,每個(gè)市的信息可以作為表里的一條記錄存放袍镀,在項(xiàng)目中進(jìn)行使用
- ①需要把外部的數(shù)據(jù)轉(zhuǎn)移到databases
copy過去的數(shù)據(jù)庫可能會多出幾張表默蚌,因?yàn)椴僮鞅旧頂?shù)據(jù)庫時(shí)用@Entity創(chuàng)建表了(所以轉(zhuǎn)移到databases時(shí),就自動創(chuàng)建表了)
/**
* assets目錄下的db轉(zhuǎn)移到databases
*
* @param context 上下文對象
* @param assetsName assets目錄下db的文件名
* @param isNeedCover 是否需要覆蓋
*/
public static void copyDBToDatabases(Context context, String assetsName, Boolean isNeedCover) {
// 獲取內(nèi)部存儲目錄
String path = context.getFilesDir().getParent();
try {
// 組裝生成db的目錄(不存在則創(chuàng)建目錄)
String dbFolder = path + File.separator + "databases" + File.separator;
File file = new File(dbFolder);
if (!file.exists()) {
file.mkdirs();
}
// 組裝db路徑
String outFileName = dbFolder + assetsName;
File dataFile = new File(outFileName);
// 文件不存在創(chuàng)建 或 文件存在且覆蓋也創(chuàng)建
if (!dataFile.exists() || (dataFile.exists() && isNeedCover)) {
if (dataFile.exists()) {
dataFile.delete();
}
InputStream myInput = context.getAssets().open(assetsName);
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) != -1) {
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
} catch (IOException e) {
Log.i("DbUtils", "error--->" + e.toString());
e.printStackTrace();
}
}
- ②需要新提供一個(gè)操作復(fù)制外部數(shù)據(jù)庫的DaoSession
DaoSession daoSession = new DaoMaster(
new DaoMaster.DevOpenHelper(this, "轉(zhuǎn)移到databases下的db文件", null)
.getWritableDb()).newSession();
- ③依然需要創(chuàng)建實(shí)體類
@nameInDb 在數(shù)據(jù)庫中的名字
用@nameInDb 限制下實(shí)體類的字段與數(shù)據(jù)庫的字段一一對應(yīng)
createInDb 是否創(chuàng)建表苇羡,默認(rèn)true
因?yàn)椴僮鞯氖峭獠繑?shù)據(jù)庫绸吸,是copy而來的,不需要創(chuàng)建表,設(shè)為false锦茁。如果實(shí)體類和copy的數(shù)據(jù)庫中的表名一致可能會報(bào)表已存在異常
@Entity(nameInDb = "user", createInDb = false)
public class User {
@Property(nameInDb = "id")
private Long id;
@Property(nameInDb = "name")
private String name;
...
}
- ④可以愉快的操作外部數(shù)據(jù)庫了