GreenDao数据库
程序员文章站
2024-03-21 09:47:04
...
GreenDao数据库
添加依赖
1 在根目录添加
buildscript {
repositories {
jcenter()
mavenCentral() // 1. add repository
}
dependencies {
classpath 'com.android.tools.build:gradle:3.5.3'
classpath 'org.greenrobot:greendao-gradle-plugin:3.3.0' //2. add plugin
}
}
2 在app中
apply plugin: 'com.android.application'
apply plugin: 'org.greenrobot.greendao' // 1.apply plugin
dependencies {
implementation 'org.greenrobot:greendao:3.3.0' // 2.add library
}
3 GreenDao 3 采用注解的方式来定义实体类,可按如下设置生成文件的目录,在app的 build.gradle 添加
greendao {
// 指定数据库schema版本号,迁移等操作会用到
schemaVersion 1
// 设置生成数据库文件的目录,默认是在build中,可以将生成的文件放到我们的java目录中
targetGenDir 'src/main/java'
// 设置生成的数据库相关文件的包名,默认为entity所在的包名
daoPackage 'com.yoho.greendao.gen'
}
编写实体类
@Entity
public class Goods {
@Id(autoincrement = true)
private Long _id = null;
private String name;
@NonNull
private String goodsId;
}
锤一下
编写SqlManager
public class SqlManager {
private static SqlManager sqlManager;
public static SqlManager getInstance() {
if (sqlManager==null){
sqlManager=new SqlManager();
}
return sqlManager;
}
private static DaoMaster daoMaster;
private DaoSession daoSession;
//使用get方法时需要传进上下文和数据库的名称
public DaoMaster getDaoMaster(Context context,String name) {
if (daoMaster==null){
DaoMaster.DevOpenHelper devOpenHelper=new DaoMaster.DevOpenHelper(context,name);
daoMaster=new DaoMaster(devOpenHelper.getWritableDb());
}
return daoMaster;
}
public DaoSession getDaoSession() {
if (daoSession==null){
daoSession=daoMaster.newSession();
}
return daoSession;
}
//关闭
public void close(){
if (daoMaster!=null){
daoMaster=null;
}
if (daoSession!=null){
daoSession.clear();
}
}
}
创建数据库
DaoMaster daoMaster = SqlManager.getInstance().getDaoMaster(this, "aaa.db");
//增加
SqlManager.getInstance().getDaoSession().insert(new SqlBean(null,"111","时间"));
//删除
SqlManager.getInstance().getDaoSession().delete(new SqlBean(Long.decode("1"),null,null));
//修改
SqlManager.getInstance().getDaoSession().update(new SqlBean(Long.decode("2"),"憨批","赵岩博"));
//查询所有
Log.i("zx", "onCreate: "+SqlManager.getInstance().getDaoSession().loadAll(SqlBean.class));