由于項(xiàng)目?jī)?yōu)化穗椅,將項(xiàng)目使用的數(shù)據(jù)庫(kù)GreenDao從2.0升級(jí)到3.0帅容,兩者在配置及使用上均有很大的不同装畅,關(guān)于GreenDao的介紹晶衷,可以在我之前的文章 GreenDao2.0使用詳解 中了解,本文主講GreenDao3.2.2的使用抄邀。
使用配置
在project的build.gradle -> buildscript -> dependencies中配置如下:
dependencies {
classpath 'com.android.tools.build:gradle:3.1.2'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'
}
在module(一般為app)的build.gradle中配置如下:
apply plugin: 'org.greenrobot.greendao'
android {
compileSdkVersion compile_sdk_version
greendao {
schemaVersion 1 //版本號(hào)耘眨,升級(jí)時(shí)可配置
daoPackage 'com.xxx.xxx.greendao'//設(shè)置DaoMaster、DaoSession境肾、Dao包名剔难,自行設(shè)置
targetGenDir 'src/main/java'//設(shè)置DaoMaster、DaoSession奥喻、Dao目錄偶宫,自行設(shè)置
}
}
dependencies {
api 'org.greenrobot:greendao:3.2.2'
}
代碼混淆
-keep class freemarker.** { *; }
-dontwarn freemarker.**
-keep class org.greenrobot.greendao.**{*;}
-dontwarn org.greenrobot.greendao.**
-keepclassmembers class * extends org.greenrobot.greendao.AbstractDao {
public static java.lang.String TABLENAME;
}
-keep class **$Properties
實(shí)現(xiàn)代碼
一. 創(chuàng)建bean對(duì)象例如MsgModel.java
/**
* Created by wangfengkai on 2018/12/6.
* Github:https://github.com/github/jxwangfengkai
*/
@Entity
public class MsgModel {
@Id(autoincrement = true)
public Long tableId;
@Transient
public String userId;
@Transient
public String content;
@Transient
public String title;
public int status;
@Transient
public Long createTime;
@Property(nameInDb = "msgId")
@Index
public int id;
@Transient
public int topicId;
public int type;
//以下代碼編譯后自動(dòng)生成
@Generated(hash = 1890461423)
public MsgModel(Long tableId, int status, int id, int type) {
this.tableId = tableId;
this.status = status;
this.id = id;
this.type = type;
}
@Generated(hash = 60092432)
public MsgModel() {
}
public Long getTableId() {
return this.tableId;
}
public void setTableId(Long tableId) {
this.tableId = tableId;
}
public int getStatus() {
return this.status;
}
public void setStatus(int status) {
this.status = status;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public int getType() {
return this.type;
}
public void setType(int type) {
this.type = type;
}
}
編寫完變量之后,編譯project:
(1)會(huì)自動(dòng)構(gòu)造方法环鲤,get,set方法纯趋。
(2)會(huì)生成 DaoMaster、DaoSession、DAOS類吵冒,類的位置位于你在 app的build.gradle的schema配置纯命。
@Entity:告訴GreenDao該對(duì)象為實(shí)體,只有被@Entity注釋的Bean類才能被dao類操作痹栖。
@Id:對(duì)象的物理Id亿汞,使用Long類型作為EntityId,否則會(huì)報(bào)錯(cuò)揪阿,(autoincrement = true)表示主鍵會(huì)自增疗我,如果false就會(huì)使用舊值。
@Property:可以自定義字段名南捂,注意外鍵不能使用該屬性吴裤。
@NotNull:屬性不能為空。
@Unique:該屬性值必須在數(shù)據(jù)庫(kù)中是唯一值黑毅。
@Generated:greenDao生產(chǎn)代碼注解嚼摩,手動(dòng)修改報(bào)錯(cuò)钦讳。
@Transient:bean中不需要存入數(shù)據(jù)庫(kù)表中的屬性字段矿瘦。
@Index(unique = true):為相應(yīng)的數(shù)據(jù)庫(kù)列創(chuàng)建數(shù)據(jù)庫(kù)索引,并向索引添加UNIQUE約束愿卒,強(qiáng)制所有值都是唯一的缚去。
二. 創(chuàng)建DaoManager類對(duì)數(shù)據(jù)庫(kù)進(jìn)行管理
public class DaoManager {
private static final String TAG = DaoManager.class.getSimpleName();
private static final String DB_NAME = "name.db";
private static DaoManager mInstance;
private DaoMaster daoMaster;
private DaoSession daoSession;
public static DaoManager getInstance() {
if (mInstance == null) {
synchronized (DaoManager.class) {
if (mInstance == null) {
mInstance = new DaoManager();
}
}
}
return mInstance;
}
private DaoManager() {
if (mInstance == null) {
DBHelper helper = new DBHelper(MCApplication.getInstance(), DB_NAME);
Database db = helper.getWritableDb();
daoMaster = new DaoMaster(db);
daoSession = daoMaster.newSession();
}
}
public DaoSession getDaoSession() {
return daoSession;
}
public DaoMaster getDaoMaster() {
return daoMaster;
}
/**
* 打開輸出日志,默認(rèn)關(guān)閉
*/
public void setDebug(boolean debug) {
QueryBuilder.LOG_SQL = debug;
QueryBuilder.LOG_VALUES = debug;
}
}
三. 創(chuàng)建DBHelper類做升級(jí)處理
public class DBHelper extends DaoMaster.OpenHelper {
private static final String TAG = DaoManager.class.getSimpleName();
public DBHelper(Context context, String dbName) {
super(context, dbName, null);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
super.onUpgrade(db, oldVersion, newVersion);
//----------------------------使用sql實(shí)現(xiàn)升級(jí)邏輯
if (oldVersion == newVersion) {
Log.e("onUpgrade", "數(shù)據(jù)庫(kù)是最新版本,無(wú)需升級(jí)" );
return;
}
Log.e("onUpgrade", "數(shù)據(jù)庫(kù)從版本" + oldVersion + "升級(jí)到版本" + newVersion);
switch (oldVersion) {
case 1:
String sql = "";
db.execSQL(sql);
case 2:
default:
break;
}
}
}
四. 創(chuàng)建ModelDaoUrils類對(duì)數(shù)據(jù)庫(kù)表進(jìn)行增刪改查等操作
例如:
modelDaoUtils = new ModelDaoUtils(context);
modelDaoUtils.insertModel(model);
類具體代碼如下:
public class MsgModelDaoUtils {
private static final String TAG = MsgModelDaoUtils.class.getSimpleName();
private DaoManager daoManager;
public MsgModelDaoUtils(Context context) {
daoManager = DaoManager.getInstance();
}
/**
* 完成msgModel記錄的插入琼开,如果表未創(chuàng)建易结,先創(chuàng)建msgModel表
*
* @return
*/
public boolean insertMsgModel(MsgModel msgModel) {
return daoManager.getDaoSession().getMsgModelDao().insert(msgModel) == -1 ? false : true;
}
/**
* 插入多條數(shù)據(jù),在子線程操作
*
* @param msgModelList
* @return
*/
public boolean insertMultMsgModel(final List<MsgModel> msgModelList) {
boolean flag = false;
try {
daoManager.getDaoSession().runInTx(new Runnable() {
@Override
public void run() {
for (MsgModel msgModel : msgModelList) {
daoManager.getDaoSession().insertOrReplace(msgModel);
}
}
});
flag = true;
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
/**
* 修改一條數(shù)據(jù)
*
* @param msgModel
* @return
*/
public boolean updateMsgModel(MsgModel msgModel) {
boolean flag = false;
try {
daoManager.getDaoSession().update(msgModel);
flag = true;
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
/**
* 刪除單條記錄
*
* @param msgModel
* @return
*/
public boolean deleteMsgModel(MsgModel msgModel) {
boolean flag = false;
try {
//按照id刪除
daoManager.getDaoSession().delete(msgModel);
flag = true;
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
/**
* 刪除所有記錄
*
* @return
*/
public boolean deleteAll() {
boolean flag = false;
try {
//按照id刪除
daoManager.getDaoSession().deleteAll(MsgModel.class);
flag = true;
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
/**
* 查詢所有記錄
*
* @return
*/
public List<MsgModel> queryAllMsgModel() {
return daoManager.getDaoSession().loadAll(MsgModel.class);
}
/**
* 根據(jù)主鍵id查詢記錄
*
* @param id
* @return
*/
public MsgModel queryMsgModelById(long id) {
return daoManager.getDaoSession().load(MsgModel.class, id);
}
/**
* 使用queryBuilder進(jìn)行查詢
*
* @return
*/
public MsgModel queryMsgModelByQueryBuilder(long id) {
try {
QueryBuilder<MsgModel> queryBuilder = daoManager.getDaoSession().queryBuilder(MsgModel.class);
return queryBuilder.where(MsgModelDao.Properties.Id.eq(id)).unique();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
五. 在Application的onCreate()方法中初始化
DaoManager.getInstance();
推新
GreenDao的使用介紹在這就結(jié)束了柜候,不過(guò)Google在2017年推出了自己的數(shù)據(jù)操作庫(kù)room搞动。接下來(lái)的文章將重點(diǎn)介紹這個(gè)谷歌官方本地?cái)?shù)據(jù)操作庫(kù)。