用过litepal,抛弃litepal是因为多层级时数据插入查询太慢了,greendao也没有进项大量数据测试,也是尝试阶段。
1.项目gradle
buildscript {
repositories {
jcenter()
mavenCentral() // add repository
}
dependencies {
classpath 'com.android.tools.build:gradle:3.5.3'
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2' // add plugin
}
}
app.gradle
apply plugin: 'org.greenrobot.greendao'
android{
greendao {
//数据库版本号,升级时修改
schemaVersion 1
//生成的DAO,DaoMaster和DaoSession的包路径。默认与表实体所在的包路径相同
daoPackage '你的包名'
//生成源文件的路径。默认源文件目录是在build目录中的(build/generated/source/greendao)
targetGenDir 'src/main/java'
}
}
dependencies {
implementation 'org.greenrobot:greendao:3.2.0'
implementation 'io.github.yuweiguocn:GreenDaoUpgradeHelper:v2.2.1'
implementation 'com.google.code.gson:gson:2.6.2'
}
2.MyApplication要进行初始化
public static MyApplication getApplication() {
return application;
}
public DaoSession getDaoSession() {
return daoSession;
}
private void initGreenDao() {
DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "greenDbbao.db");
SQLiteDatabase db = helper.getWritableDatabase();
DaoMaster daoMaster = new DaoMaster(db);
daoSession = daoMaster.newSession();
}
3.Bean类
Person.class
@Entity是将类进行greendao自动生成标识
@Id 是表key ,long型,我习惯单独定义方便控制
@Convert是将子类或者list转换为String
Student_Convert 和StudentList_Convert要提前写好
package com.tayh.buttontest.greendao;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.greenrobot.greendao.annotation.Convert;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Generated;
import org.greenrobot.gr