1.在工程配置的buildscript中的dependencies里添加
buildscript{
repositories{
jcenter()
mavenCentral()// 添加的代码
}
dependencies{
classpath'com.android.tools.build:gradle:2.3.3'
classpath'org.greenrobot:greendao-gradle-plugin:3.2.2'// add plugin
}
}
2.在项目配置的头部添加插件
apply plugin: 'org.greenrobot.greendao' // apply plugin
3.然后添加依赖
implementation 'org.greenrobot:greendao:3.2.2' // add library
implementation 'org.greenrobot:greendao-generator:3.2.2'
4.最后初始化GreenDao的配置
greendao{
schemaVersion 1 //数据库版本号
daoPackage 'com.example.greendao.dao' //数据库全路径
targetGenDir 'src/main/java' //存放位置
//如果还导不进去尝试着把 targetGenDir 'src/main/java' 存放位置注释
}
schemaVersion–> 指定数据库schema版本号,迁移等操作会用到;
daoPackage --> dao的包名,包名默认是entity所在的包;
targetGenDir --> 生成数据库文件的目录;
二.代码
双检锁单例模式:得到表对象
public static DbHelp getInstance() {
if (instance==null){
synchronized (DbHelp.class){
if (instance==null){
instance=new DbHelp();
}
}
}
return instance;
}
//创建数据库
private DbHelp(){
DaoMaster.DevOpenHelper devOpenHelper=new DaoMaster.DevOpenHelper(GreenDaoApplication.getApp(),"s.db");
//获取读写对象
DaoMaster daoMaster =new DaoMaster(devOpenHelper.getWritableDb());
//获取管理器
DaoSession daoSession = daoMaster.newSession();
//获取表对象
studentBeanDao = daoSession.getStudentBeanDao();
}
获取整个App的上下文
private static GreenDaoApplicationapp;
@Override
public void onCreate() {
super.onCreate();
app=this;
}
public static GreenDaoApplication getApp() {
return app;
}
使用Greendao实现增删改查
//添加
public void insert(StudentBean studentBean){
studentBeanDao.insertOrReplace(studentBean);
}
//删除
public void delete(StudentBean studentBean){
studentBeanDao.delete(studentBean);
}
//修改
public void updata(StudentBean studentBean){
studentBeanDao.update(studentBean);
}
//查询全部
public List queryAll(){
return studentBeanDao.queryBuilder().list();
}