为什么使用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