(一)使用配置說明:
首先在整個(gè)工程Project的build.gradle中配置:
classpath'org.greenrobot:greendao-gradle-plugin:3.2.0'
然后在項(xiàng)目app所對(duì)應(yīng)的build.gradle中配置:
apply plugin: 'org.greenrobot.greendao'
greendao{
schemaVersion 1 //數(shù)據(jù)庫(kù)版本號(hào),如果數(shù)據(jù)庫(kù)需要升級(jí),直接在此修改版本號(hào)即可
// daoPackage 'com.anye.greendao.gen' //dao包名,默認(rèn)是entity所在的包
targetGenDir 'src/main/java' //數(shù)據(jù)庫(kù)文件的目錄
}
dependencies {
compile 'org.greenrobot:greendao:3.2.0'
...
}
(二)常用操作說明:
(一) @Entity 定義實(shí)體
@nameInDb 在數(shù)據(jù)庫(kù)中的名字,如不寫則為實(shí)體中類名
@indexes 索引
@createInDb 是否創(chuàng)建表,默認(rèn)為true,false時(shí)不創(chuàng)建
@schema 指定架構(gòu)名稱為實(shí)體
@active 無論是更新生成都刷新
(二) @Id
(三) @NotNull 不為null
(四) @Unique 唯一約束
(五) @ToMany 一對(duì)多
(六) @OrderBy 排序
(七) @ToOne 一對(duì)一
(八) @Transient 不存儲(chǔ)在數(shù)據(jù)庫(kù)中
(九) @generated 由greendao產(chǎn)生的構(gòu)造函數(shù)或方法
lt:小于 le:小于等于
gt:大于 ge:大于等于
eq:等于
orderAsc: 升序 orderDesc:倒序
or: 或 and:與(默認(rèn)為and)
(三)使用(項(xiàng)目聊天中使用):
1.先創(chuàng)建數(shù)據(jù)庫(kù)實(shí)體類,聊天記錄與聊天列表
/**
*聊天記錄數(shù)據(jù)庫(kù)
*/
@Entity
public class ChatRecord {
@Id(autoincrement = true)
@Unique
private Long mainKey; //主鍵自增長(zhǎng),不可重復(fù),作為不同記錄對(duì)象的標(biāo)識(shí),傳入?yún)?shù)對(duì)象時(shí)不要傳入
@Property(nameInDb = "content")private String content;
@Property(nameInDb = "mine")private boolean mine;
@Property(nameInDb = "timestamp")private Long timestamp;
@Property(nameInDb = "to_id")private String to_id;
@Property(nameInDb = "id")private String id;
@Property(nameInDb = "send_status")private int send_status; //0:成功 1:失敗 2:發(fā)送中
@Property(nameInDb = "contentstyle")private int contentStyle; //0:圖片 1:文本
@Property(nameInDb = "priid")private String priid; //區(qū)分不同公司
}
/**
* 聊天列表數(shù)據(jù)庫(kù)
*/
@Entity
public class ChatList {
@Id(autoincrement = true)
@Unique
private Long mainKey; //主鍵自增長(zhǎng),不可重復(fù),作為不同記錄對(duì)象的標(biāo)識(shí),傳入?yún)?shù)對(duì)象時(shí)不要傳入
@Property(nameInDb = "CROP")private String corp;
@Property(nameInDb = "UNREADCOUNT")private int unReadCount;
@Property(nameInDb = "avatar")private String avatar;
@Property(nameInDb = "content")private String content;
@Property(nameInDb = "message_type")private String message_type;
@Property(nameInDb = "timestamp")private Long timestamp;
@Property(nameInDb = "to_avatar")private String to_avatar;
@Property(nameInDb = "to_id")private String to_id;
@Property(nameInDb = "to_username")private String to_username;
@Property(nameInDb = "type")private String type;
@Property(nameInDb = "id")private String id;
@Property(nameInDb = "username")private String username;
@Property(nameInDb = "message_type_id")private String message_type_id;
@Property(nameInDb = "priid")private String priid; //區(qū)分不同公司
}
然后使用studio中的小錘子MakeProject或者build或者clean(有時(shí)build、clean時(shí)會(huì)出現(xiàn)不自動(dòng)生成的問題,反正小錘子挺好用的~)會(huì)自動(dòng)生成beanDAO、DaoMaster、DaoSession這些類。。。不需要我們操作!
2.上面的操作數(shù)據(jù)庫(kù)就已經(jīng)創(chuàng)建好了 ,接下來就要開始使用了,使用之前要先來個(gè)工具類,可根據(jù)自己項(xiàng)目自行修改封裝,方便使用:
/**
* Created by zzb on 2016/11/7.
* 消息列表util
*/
public class ChatDbUtils {
private static ChatDbUtils dbUtils;
private final static String dbName = "dzfim.db";
private DaoMaster.DevOpenHelper openHelper;
private Context context;
private ChatDbUtils() {
context = DZFApp.mContext;
openHelper = new DaoMaster.DevOpenHelper(context, dbName, null);
}
/**
* 獲取單例
*
* @return
*/
public static ChatDbUtils getInstance() {
if (dbUtils == null) {
synchronized (ChatDbUtils.class) {
if (dbUtils == null) {
dbUtils = new ChatDbUtils();
}
}
}
return dbUtils;
}
/**
* 獲取可讀數(shù)據(jù)庫(kù)
*/
private SQLiteDatabase getReadableDatabase() {
if (openHelper == null) {
openHelper = new DaoMaster.DevOpenHelper(context, dbName, null);
}
SQLiteDatabase db = openHelper.getReadableDatabase();
return db;
}
/**
* 獲取可寫數(shù)據(jù)庫(kù)
*/
private SQLiteDatabase getWritableDatabase() {
if (openHelper == null) {
openHelper = new DaoMaster.DevOpenHelper(context, dbName, null);
}
SQLiteDatabase db = openHelper.getWritableDatabase();
return db;
}
/****************************************************************************************************************************/
/************************************列表中使用的方法********************************************************/
/**
* 增、改,新的好友增加,出現(xiàn)過的更新
*
* @param info id、to_id 字段不能為空
*/
public void saveList(ChatList info) {
DaoMaster daoMaster = new DaoMaster(getWritableDatabase());
DaoSession daoSession = daoMaster.newSession();
ChatListDao chatListDao = daoSession.getChatListDao();
ChatList chatList = querySingleList(info.getId(), info.getTo_id(), info.getPriid());
if (chatList != null) {
info.setMainKey(chatList.getMainKey());
}
chatListDao.insertOrReplace(info);
}
/**返回保存列表后的消息條數(shù)*/
public int saveListToAddUnRead(ChatList info) {
DaoMaster daoMaster = new DaoMaster(getWritableDatabase());
DaoSession daoSession = daoMaster.newSession();
ChatListDao chatListDao = daoSession.getChatListDao();
ChatList chatList = querySingleList(info.getId(), info.getTo_id(), info.getPriid()); //先判斷此對(duì)話是否存在
if (chatList != null) {
info.setMainKey(chatList.getMainKey());
info.setUnReadCount(chatList.getUnReadCount() + 1);
} else {
info.setUnReadCount(1);
}
chatListDao.insertOrReplace(info);
return info.getUnReadCount();
}
/**
* 保存、更新列表集合
*
* @param infos
*/
public void saveLists(List<ChatList> infos) {
for (ChatList info :
infos) {
saveList(info);
}
}
/**
* 刪除當(dāng)前好友列表
*
* @param info
*/
public void deleteList(ChatList info) {
try {
DaoMaster daoMaster = new DaoMaster(getWritableDatabase());
DaoSession daoSession = daoMaster.newSession();
ChatListDao chatListDao = daoSession.getChatListDao();
chatListDao.delete(info);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 刪除所有通知類型
*
* @param userId
* @param priid
*/
public void deleteAllNoticeList(String userId, String priid) {
try {
DaoMaster daoMaster = new DaoMaster(getReadableDatabase());
DaoSession daoSession = daoMaster.newSession();
ChatListDao chatListDao = daoSession.getChatListDao();
QueryBuilder<ChatList> qb = chatListDao.queryBuilder();
DeleteQuery<ChatList> bd = qb.where(ChatListDao.Properties.Id.eq(userId),
ChatListDao.Properties.Priid.eq(priid),
ChatListDao.Properties.Type.eq("notice")).buildDelete();
bd.executeDeleteWithoutDetachingEntities();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 通過指定條件刪除
*
* @param userId
* @param to_userId
*/
public void deleteList(String userId, String to_userId, String priid) {
try {
DaoMaster daoMaster = new DaoMaster(getReadableDatabase());
DaoSession daoSession = daoMaster.newSession();
ChatListDao chatListDao = daoSession.getChatListDao();
QueryBuilder<ChatList> qb = chatListDao.queryBuilder();
DeleteQuery<ChatList> bd = qb.where(ChatListDao.Properties.Id.eq(userId),
ChatListDao.Properties.To_id.eq(to_userId),
qb.or(qb.and(ChatListDao.Properties.Priid.eq(priid), ChatListDao.Properties.Type.eq("notice")),
ChatListDao.Properties.Type.eq("friend"))).buildDelete();
bd.executeDeleteWithoutDetachingEntities();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 通過時(shí)間查找所有列表,列表只保存每個(gè)好友聊天最后一條數(shù)據(jù),按時(shí)間倒序
*/
public List<ChatList> queryAllLists(String userId, String priid) {
try {
DaoMaster daoMaster = new DaoMaster(getReadableDatabase());
DaoSession daoSession = daoMaster.newSession();
ChatListDao chatListDao = daoSession.getChatListDao();
QueryBuilder<ChatList> qb = chatListDao.queryBuilder();
//條件: id & ((notice & priid) | friend)
qb.where(ChatListDao.Properties.Id.eq(userId),
qb.or(qb.and(ChatListDao.Properties.Priid.eq(priid), ChatListDao.Properties.Type.eq("notice")), ChatListDao.Properties.Type.eq("friend")))
.orderDesc(ChatListDao.Properties.Timestamp);
List<ChatList> chatLists = qb.list();
return chatLists;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 分頁(yè)查詢,每頁(yè)10條數(shù)據(jù),按時(shí)間降序
*
* @param userId
* @param page 查詢的頁(yè)數(shù),從0開始
* @return
*/
public List<ChatList> queryPageLists(String userId, String priid, int page) {
try {
DaoMaster daoMaster = new DaoMaster(getReadableDatabase());
DaoSession daoSession = daoMaster.newSession();
ChatListDao chatListDao = daoSession.getChatListDao();
QueryBuilder<ChatList> qb = chatListDao.queryBuilder();
qb.where(ChatListDao.Properties.Id.eq(userId),
qb.or(qb.and(ChatListDao.Properties.Priid.eq(priid), ChatListDao.Properties.Type.eq("notice")), ChatListDao.Properties.Type.eq("friend")))
.orderDesc(ChatListDao.Properties.Timestamp)
.offset(page * 10).limit(10);
List<ChatList> chatLists = qb.list();
return chatLists;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 查詢列表中指定好友的數(shù)據(jù)
*
* @param userId
* @param to_userId
* @return 指定好友的單條數(shù)據(jù)
*/
public ChatList querySingleList(String userId, String to_userId, String priid) {
try {
DaoMaster daoMaster = new DaoMaster(getReadableDatabase());
DaoSession daoSession = daoMaster.newSession();
ChatListDao chatListDao = daoSession.getChatListDao();
QueryBuilder<ChatList> qb = chatListDao.queryBuilder();
qb.where(ChatListDao.Properties.Id.eq(userId),
ChatListDao.Properties.To_id.eq(to_userId),
qb.or(qb.and(ChatListDao.Properties.Priid.eq(priid), ChatListDao.Properties.Type.eq("notice")), ChatListDao.Properties.Type.eq("friend")));
ChatList chatList = qb.unique();
return chatList;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 獲取未讀消息總數(shù)
*
* @param user
* @return
*/
public int getAllUnReadCount(String user, String priid) {
List<ChatList> chatLists = queryAllLists(user, priid);
int count = 0;
if (chatLists != null) {
for (ChatList chatList :
chatLists) {
count += chatList.getUnReadCount();
}
}
return count;
}
/**
* 所有聊天類型的未讀數(shù)
*/
public int getChatMessageUnReadCount(String userId, String priid) {
int count = 0;
try {
DaoMaster daoMaster = new DaoMaster(getReadableDatabase());
DaoSession daoSession = daoMaster.newSession();
ChatListDao chatListDao = daoSession.getChatListDao();
QueryBuilder<ChatList> qb = chatListDao.queryBuilder();
qb.where(ChatListDao.Properties.Id.eq(userId), ChatListDao.Properties.Type.eq("friend")).orderDesc(ChatListDao.Properties.Timestamp);
List<ChatList> chatLists = qb.list();
for (ChatList chatList :
chatLists) {
count += chatList.getUnReadCount();
}
} catch (Exception e) {
e.printStackTrace();
}
return count;
}
/**
* 所有通知類型的未讀數(shù)
*/
public int getNoticeUnReadCount(String userId, String priid) {
int count = 0;
try {
DaoMaster daoMaster = new DaoMaster(getReadableDatabase());
DaoSession daoSession = daoMaster.newSession();
ChatListDao chatListDao = daoSession.getChatListDao();
QueryBuilder<ChatList> qb = chatListDao.queryBuilder();
qb.where(ChatListDao.Properties.Id.eq(userId), ChatListDao.Properties.Priid.eq(priid), ChatListDao.Properties.Type.eq("notice")).orderDesc(ChatListDao.Properties.Timestamp);
List<ChatList> chatLists = qb.list();
for (ChatList chatList :
chatLists) {
count += chatList.getUnReadCount();
}
} catch (Exception e) {
e.printStackTrace();
}
return count;
}
/**
* 使當(dāng)前好友的未讀數(shù)為0,已讀
*/
public void markMessagesAsRead(ChatList chatList) {
chatList.setUnReadCount(0);
saveList(chatList);
}
public void markMessagesAsRead(String userId, String to_userId, String priid) {
ChatList chatList = querySingleList(userId, to_userId, priid);
if (chatList != null) {
chatList.setUnReadCount(0);
DaoMaster daoMaster = new DaoMaster(getWritableDatabase());
DaoSession daoSession = daoMaster.newSession();
ChatListDao chatListDao = daoSession.getChatListDao();
chatListDao.insertOrReplace(chatList);
}
}
/****************************************************************************************************************************/
/************************************聊天記錄方法********************************************************/
/**
* 增、改
*
* @param info
*/
public void saveRecord(ChatRecord info) {
DaoMaster daoMaster = new DaoMaster(getWritableDatabase());
DaoSession daoSession = daoMaster.newSession();
ChatRecordDao chatRecordDao = daoSession.getChatRecordDao();
chatRecordDao.insertOrReplace(info);
}
/**
* 刪除一條
*
* @param info
*/
public void deleteRecord(ChatRecord info) {
try {
DaoMaster daoMaster = new DaoMaster(getWritableDatabase());
DaoSession daoSession = daoMaster.newSession();
ChatRecordDao chatRecordDao = daoSession.getChatRecordDao();
chatRecordDao.delete(info);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 清空當(dāng)前好友聊天記錄
*/
public void deleteAllRecords(String userId, String to_userId) {
List<ChatRecord> chatRecords = queryAllRecords(userId, to_userId);
for (ChatRecord chatRecord :
chatRecords) {
deleteRecord(chatRecord);
}
}
/**
* 查找所有數(shù)據(jù),按時(shí)間升序
*/
public List<ChatRecord> queryAllRecords(String userId, String to_userId) {
try {
DaoMaster daoMaster = new DaoMaster(getReadableDatabase());
DaoSession daoSession = daoMaster.newSession();
ChatRecordDao chatRecordDao = daoSession.getChatRecordDao();
QueryBuilder<ChatRecord> qb = chatRecordDao.queryBuilder();
qb.where(ChatRecordDao.Properties.Id.eq(userId),
ChatRecordDao.Properties.To_id.eq(to_userId))
.orderAsc(ChatRecordDao.Properties.Timestamp);
List<ChatRecord> list = qb.list();
return list;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 分頁(yè)查詢,每頁(yè)10條數(shù)據(jù)
*
* @param userId
* @param to_userId
* @param mainKey 使用主鍵來作為頁(yè)數(shù)查詢的主要條件
* @return
*/
public List<ChatRecord> queryPageRecords(String userId, String to_userId, long mainKey) {
try {
DaoMaster daoMaster = new DaoMaster(getReadableDatabase());
DaoSession daoSession = daoMaster.newSession();
ChatRecordDao chatRecordDao = daoSession.getChatRecordDao();
QueryBuilder<ChatRecord> qb = chatRecordDao.queryBuilder();
if (mainKey == -1) { //=-1則是剛進(jìn)入chatActivity的首次查詢,不傳主鍵
qb.where(ChatRecordDao.Properties.Id.eq(userId),
ChatRecordDao.Properties.To_id.eq(to_userId))
.orderDesc(ChatRecordDao.Properties.Timestamp)
.limit(10);
} else { //
qb.where(ChatRecordDao.Properties.Id.eq(userId),
ChatRecordDao.Properties.To_id.eq(to_userId), ChatRecordDao.Properties.MainKey.lt(mainKey)) //
.orderDesc(ChatRecordDao.Properties.Timestamp)
.limit(10);
}
List<ChatRecord> list = qb.list();
Collections.reverse(list);
return list;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 按時(shí)間升序查詢所有圖片記錄,點(diǎn)擊查看大圖使用
*
* @param userId
* @param to_userId
* @return
*/
public List<ChatRecord> queryAllImageRecords(String userId, String to_userId) {
try {
DaoMaster daoMaster = new DaoMaster(getReadableDatabase());
DaoSession daoSession = daoMaster.newSession();
ChatRecordDao chatRecordDao = daoSession.getChatRecordDao();
QueryBuilder<ChatRecord> qb = chatRecordDao.queryBuilder();
qb.where(ChatRecordDao.Properties.Id.eq(userId),
ChatRecordDao.Properties.To_id.eq(to_userId),
ChatRecordDao.Properties.ContentStyle.eq(0)) //0代表圖片
.orderAsc(ChatRecordDao.Properties.Timestamp);
List<ChatRecord> list = qb.list();
return list;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
3.工具類封裝好之后,使用起來就簡(jiǎn)單了,直接上代碼:
保存或修改數(shù)據(jù)(無則添加,有則修改):
ChatDbUtils.getInstance().saveRecord(ChatRecord info)
查詢數(shù)據(jù):
ChatDbUtils.getInstance().queryAllRecords(String userId, String to_userId)
刪除數(shù)據(jù):
//通過對(duì)象刪除
ChatDbUtils.getInstance().deleteRecord(ChatRecord info)
//指定條件刪除
ChatDbUtils.getInstance().deleteAllNoticeList(String userId, String priid)
到這里基本的使用就介紹完了,大家可根據(jù)自己項(xiàng)目需求,自行進(jìn)行修改使用!
這里附上一款使用Kotlin、GreenDao幫朋友寫的一款考試作弊軟件,上面用到的知識(shí)在這里都有用到:
https://github.com/zzbandroid/ReadApp