GreenDao3.2.2使用详解

由于项目优化,将项目使用的数据库GreenDao从2.0升级到3.0,两者在配置及使用上均有很大的不同,关于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  //版本号,升级时可配置
        daoPackage 'com.xxx.xxx.greendao'//设置DaoMaster、DaoSession、Dao包名,自行设置
        targetGenDir 'src/main/java'//设置DaoMaster、DaoSession、Dao目录,自行设置
    }
}
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
实现代码

一. 创建bean对象例如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;

//以下代码编译后自动生成
@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)会自动构造方法,get,set方法。
(2)会生成 DaoMaster、DaoSession、DAOS类,类的位置位于你在 app的build.gradle的schema配置。
@Entity:告诉GreenDao该对象为实体,只有被@Entity注释的Bean类才能被dao类操作。
@Id:对象的物理Id,使用Long类型作为EntityId,否则会报错,(autoincrement = true)表示主键会自增,如果false就会使用旧值。
@Property:可以自定义字段名,注意外键不能使用该属性。
@NotNull:属性不能为空。
@Unique:该属性值必须在数据库中是唯一值。
@Generated:greenDao生产代码注解,手动修改报错。
@Transient:bean中不需要存入数据库表中的属性字段。
@Index(unique = true):为相应的数据库列创建数据库索引,并向索引添加UNIQUE约束,强制所有值都是唯一的。

二. 创建DaoManager类对数据库进行管理

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;
}

/**
 * 打开输出日志,默认关闭
 */
public void setDebug(boolean debug) {
    QueryBuilder.LOG_SQL = debug;
    QueryBuilder.LOG_VALUES = debug;
}
}

三. 创建DBHelper类做升级处理

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实现升级逻辑
    if (oldVersion == newVersion) {
        Log.e("onUpgrade", "数据库是最新版本,无需升级" );
        return;
    }
    Log.e("onUpgrade", "数据库从版本" + oldVersion + "升级到版本" + newVersion);
    switch (oldVersion) {
        case 1:
            String sql = "";
            db.execSQL(sql);
        case 2:
        default:
            break;
    }
}
}

四. 创建ModelDaoUrils类对数据库表进行增删改查等操作
例如:

 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记录的插入,如果表未创建,先创建msgModel表
 *
 * @return
 */
public boolean insertMsgModel(MsgModel msgModel) {
    return daoManager.getDaoSession().getMsgModelDao().insert(msgModel) == -1 ? false : true;
}

/**
 * 插入多条数据,在子线程操作
 *
 * @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;
}

/**
 * 修改一条数据
 *
 * @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);
}

/**
 * 根据主键id查询记录
 *
 * @param id
 * @return
 */
public MsgModel queryMsgModelById(long id) {
    return daoManager.getDaoSession().load(MsgModel.class, id);
}

/**
 * 使用queryBuilder进行查询
 *
 * @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的使用介绍在这就结束了,不过Google在2017年推出了自己的数据操作库room。接下来的文章将重点介绍这个谷歌官方本地数据操作库。

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

推荐阅读更多精彩内容