greenDao的简单使用

为什么使用greenDao数据库框架?https://juejin.im/post/5958fe70f265da6c49777c94

greenDAO 是基于AndroidSQLite的最快、性能最强悍的数据库框架,因为他不涉及反射,靠的是代码辅助生成。

集成greenDao:

1. build.gradle (project)——

buildscript {
    
    repositories {
        google()
        jcenter()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.0'
        classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

2.build.gradle(module)——

apply plugin: 'org.greenrobot.greendao'

android{

greendao{
    //指定数据库schema版本号,迁移等操作会用到
    schemaVersion 3
    //DaoSession、DaoMaster以及所有实体类的dao生成的目录,默认为你的entity所在的包名
    //daoPackage 包名
    daoPackage 'com.able.greendaodemo.db'
    //自定义生成数据库文件的目录了,可以将生成的文件放到我们的java目录中,而不是build中,这样就不用额外的设置资源目录了
    //工程路径
    targetGenDir 'src/main/java'
}
dependencies{
implementation 'org.greenrobot:greendao:3.2.2'
}

}

3. 

Application 类

oncreate()中添加

DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "users-db");
Database db = helper.getWritableDb();
daoSession = new DaoMaster(db).newSession();

然后get:

public DaoSession getDaoSession() {
    return daoSession;
}

在使用时插入数据:

DaoSession daoSession = ((MyApp) getApplication()).getDaoSession();
userDao = daoSession.getUserDao();
User user = new User(null,"测试",22);
try {
//插入
    userDao.insert(user);
}catch (Exception e){
    Log.i("异常", e.toString());
}

具体代码可在我的github出下载

https://github.com/zsq7777/GreenDaoDemo.git

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值