(一)使用配置说明:
首先在整个工程Project的build.gradle中配置:
classpath'org.greenrobot:greendao-gradle-plugin:3.2.0'
然后在项目app所对应的build.gradle中配置:
apply plugin: 'org.greenrobot.greendao'
greendao{
schemaVersion 1 //数据库版本号,如果数据库需要升级,直接在此修改版本号即可
// daoPackage 'com.anye.greendao.gen' //dao包名,默认是entity所在的包
targetGenDir 'src/main/java' //数据库文件的目录
}
dependencies {
compile 'org.greenrobot:greendao:3.2.0'
...
}
(二)常用操作说明:
(一) @Entity 定义实体
@nameInDb 在数据库中的名字,如不写则为实体中类名
@indexes 索引
@createInDb 是否创建表,默认为true,false时不创建
@schema 指定架构名称为实体
@active 无论是更新生成都刷新
(二) @Id
(三) @NotNull 不为null
(四) @Unique 唯一约束
(五) @ToMany 一对多
(六) @OrderBy 排序
(七) @ToOne 一对一
(八) @Transient 不存储在数据库中
(九) @generated 由greendao产生的构造函数或方法
lt:小于 le:小于等于
gt:大于 ge:大于等于
eq:等于
orderAsc: 升序 orderDesc:倒序
or: 或 and:与(默认为and)
(三)使用(项目聊天中使用):
1.先创建数据库实体类,聊天记录与聊天列表
/**
*聊天记录数据库
*/
@Entity
public class ChatRecord {
@Id(autoincrement = true)
@Unique
private Long mainKey; //主键自增长,不可重复,作为不同记录对象的标识,传入参数对象时不要传入
@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:发送中
@Property(nameInDb = "contentstyle")private int contentStyle; //0:图片 1:文本
@Property(nameInDb = "priid")private String priid; //区分不同公司
}
/**
* 聊天列表数据库
*/
@Entity
public class ChatList {
@Id(autoincrement = true)
@Unique
private Long mainKey; //主键自增长,不可重复,作为不同记录对象的标识,传入参数对象时不要传入
@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; //区分不同公司
}
然后使用studio中的小锤子MakeProject或者build或者clean(有时build、clean时会出现不自动生成的问题,反正小锤子挺好用的~)会自动生成beanDAO、DaoMaster、DaoSession这些类。。。不需要我们操作!
2.上面的操作数据库就已经创建好了 ,接下来就要开始使用了,使用之前要先来个工具类,可根据自己项目自行修改封装,方便使用:
/**
* 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;
}
/**
* 获取可读数据库
*/
private SQLiteDatabase getReadableDatabase() {
if (openHelper == null) {
openHelper = new DaoMaster.DevOpenHelper(context, dbName, null);
}
SQLiteDatabase db = openHelper.getReadableDatabase();
return db;
}
/**
* 获取可写数据库
*/
private SQLiteDatabase getWritableDatabase() {
if (openHelper == null) {
openHelper = new DaoMaster.DevOpenHelper(context, dbName, null);
}
SQLiteDatabase db = openHelper.getWritableDatabase();
return db;
}
/****************************************************************************************************************************/
/************************************列表中使用的方法********************************************************/
/**
* 增、改,新的好友增加,出现过的更新
*
* @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);
}
/**返回保存列表后的消息条数*/
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()); //先判断此对话是否存在
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);
}
}
/**
* 删除当前好友列表
*
* @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();
}
}
/**
* 通过时间查找所有列表,列表只保存每个好友聊天最后一条数据,按时间倒序
*/
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;
}
/**
* 分页查询,每页10条数据,按时间降序
*
* @param userId
* @param page 查询的页数,从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;
}
/**
* 查询列表中指定好友的数据
*
* @param userId
* @param to_userId
* @return 指定好友的单条数据
*/
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;
}
/**
* 获取未读消息总数
*
* @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;
}
/**
* 所有聊天类型的未读数
*/
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;
}
/**
* 所有通知类型的未读数
*/
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;
}
/**
* 使当前好友的未读数为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();
}
}
/**
* 清空当前好友聊天记录
*/
public void deleteAllRecords(String userId, String to_userId) {
List<ChatRecord> chatRecords = queryAllRecords(userId, to_userId);
for (ChatRecord chatRecord :
chatRecords) {
deleteRecord(chatRecord);
}
}
/**
* 查找所有数据,按时间升序
*/
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;
}
/**
* 分页查询,每页10条数据
*
* @param userId
* @param to_userId
* @param mainKey 使用主键来作为页数查询的主要条件
* @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则是刚进入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;
}
/**
* 按时间升序查询所有图片记录,点击查看大图使用
*
* @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.工具类封装好之后,使用起来就简单了,直接上代码:
保存或修改数据(无则添加,有则修改):
ChatDbUtils.getInstance().saveRecord(ChatRecord info)
查询数据:
ChatDbUtils.getInstance().queryAllRecords(String userId, String to_userId)
删除数据:
//通过对象删除
ChatDbUtils.getInstance().deleteRecord(ChatRecord info)
//指定条件删除
ChatDbUtils.getInstance().deleteAllNoticeList(String userId, String priid)
到这里基本的使用就介绍完了,大家可根据自己项目需求,自行进行修改使用!
这里附上一款使用Kotlin、GreenDao帮朋友写的一款考试作弊软件,上面用到的知识在这里都有用到:
https://github.com/zzbandroid/ReadApp