Android GreenDao3.0项目使用

(一)使用配置说明:

首先在整个工程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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,457评论 5 459
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,837评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,696评论 0 319
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,183评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,057评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,105评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,520评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,211评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,482评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,574评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,353评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,213评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,576评论 3 298
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,897评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,174评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,489评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,683评论 2 335

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,497评论 18 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,050评论 25 707
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,678评论 6 342
  • 1.介绍 如果你正在查阅build.gradle文件的所有可选项,请点击这里进行查阅:DSL参考 1.1新构建系统...
    Chuckiefan阅读 12,094评论 8 72
  • 一直爱看书买书,却很少写东西。每次遇到要写东西的情况,总是到最后期限甚至是过了最后期限才勉强凑出一篇来。期间各种焦...
    喜可阅读 230评论 0 0