GreenDao 的简介和使用
greenDAO简介
greenDAO是一款开源的面向 Android 的轻便、快捷的 ORM 框架,将 Java 对象映射到SQLite数据库中,我们操作数据库的时候,不再需要编写复杂的 SQL语句, 在性能方面,greenDAO针对 Android 进行了高度优化, 最小的内存开销 、依赖体积小 同时还是支持数据库加密。
ORM 框架有很多,比较著名的有 OrmLite , ActiveAndroid 等
greenDAO项目地址:https://github.com/greenrobot/greenDAO
视频讲解链接
https://www.bilibili.com/video/BV1Qt4y117Up
greenDAO集成
第一步 在项目的build.gradle 文件中配置classpath
buildscript { apply from: 'script.gradle', to: buildscript repositories { jcenter() maven {url 'https://maven.google.com'} google() } dependencies { classpath 'com.android.tools.build:gradle:3.2.1' classpath 'org.greenrobot:greendao-gradle-plugin:3.2.0' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files }}
第二步 在app的build.gradle 文件中引入greenDao插件
apply plugin: 'org.greenrobot.greendao'
第三步 在app的build.gradle 文件中导入greenDao依赖包
implementation 'org.greenrobot:greendao-generator:3.2.2'
第四步 在app的build.gradle 文件中配置数据库相关信息
android { compileSdkVersion 28 buildToolsVersion '28.0.3' aaptOptions.cruncherEnabled = false aaptOptions.useNewCruncher = false greendao { schemaVersion 1//数据库版本号 daoPackage 'cn.***.greendao'//设置DaoMaster、DaoSession、Dao包名 targetGenDir 'src/main/java'//设置DaoMaster、DaoSession、Dao目录 //targetGenDirTest:设置生成单元测试目录 //generateTests:设置自动生成单元测试用例 } }
这样greenDao就集成好了,下面我们就看怎么使用greenDao.
greenDao的使用
1,新建实体类
新建一个实体类,对整个实体类使用注解 @Entity
@Entity public class Student { }
接下来添加类的属性
@Entitypublic class Student { @Id //@id 是设置主键,我们用Long类型是可以使主键id自增 private Long id; //@Preoerty这个是数据库表的列名,nameInDb = "student_name" 是指表中的列名为“student_name @Property(nameInDb = "student_name") private String studentName;;}
类的属性写好之后,这个时候我们只需要编译一下代码greenDao 会自动创建类的get、set方法和构造方法,同时会在我们配置的greendao的文件中自动生成DaoMaster、DaoSession和StudentDao.
这里需要记住,如果你不是第一次新增类的话,在新增完之后是要升级我们greendao配置文件中,我们的数据库版本号的,负责可能会报错,这个时候我们只需要把 schemaVersion 它的值加一就可以了
schemaVersion 1//数据库版本号
接着我们在green_dao这个包下面新建一个DaoManager的类,方便获取我们的DaoSession,让我们使用起来更方便,快捷!一下是我们DaoManager的代码。
public class DaoManager { private Context mContext; //创建数据库的名字 private static final String DB_NAME = "aaa.db"; //多线程中要被共享的使用volatile关键字修饰 GreenDao管理类 private volatile static DaoManager mInstance; //它里边实际上是保存数据库的对象 private static DaoMaster mDaoMaster; //创建数据库的工具 private static DaoMaster.DevOpenHelper mHelper; //管理gen里生成的所有的Dao对象里边带有基本的增删改查的方法 private static DaoSession mDaoSession; private DaoManager() { } /** * 单例模式获得操作数据库对象 * * @return */ public static DaoManager getInstance() { if (mInstance == null) { synchronized (DaoManager.class) { if (mInstance == null) { mInstance = new DaoManager(); } } } return mInstance; } /** * 初始化上下文创建数据库的时候使用 */ public void init(Context context) { this.mContext = context; } /** * 判断是否有存在数据库,如果没有则创建 * * @return */ public DaoMaster getDaoMaster() { if (mDaoMaster == null) { mHelper = new DaoMaster.DevOpenHelper(mContext, DB_NAME, null); mDaoMaster = new DaoMaster(mHelper.getWritableDatabase()); } return mDaoMaster; } /** * 完成对数据库的添加、删除、修改、查询操作, * * @return */ public DaoSession getDaoSession() { if (mDaoSession == null) { if (mDaoMaster == null) { mDaoMaster = getDaoMaster(); } mDaoSession = mDaoMaster.newSession(); } return mDaoSession; } /** * 关闭所有的操作,数据库开启后,使用完毕要关闭 */ public void closeConnection() { closeHelper(); closeDaoSession(); } public void closeHelper() { if (mHelper != null) { mHelper.close(); mHelper = null; } } public void closeDaoSession() { if (mDaoSession != null) { mDaoSession.clear(); mDaoSession = null; } }}
我们在MyApplication里面初始化一下我们的DaoManager
public class MyApplication extends Application { @Override public void onCreate() { super.onCreate(); DaoManager.getInstance().init(this); DaoManager.getInstance().getDaoMaster(); }}
下面我们就可以使用了!
2 greenDao 新增数据
A 新增一条数据
//获取StudentDaoStudentDao studentDao = DaoManager.getInstance().getDaoSession().getStudentDao();//新建一个SrudentStudent student = new Student(null,"张三");//ID可以自增所以我们传null//使用studentDao 新增一个studentstudentDao.insert(student);
B 批量新增
StudentDao studentDao = DaoManager.getInstance().getDaoSession().getStudentDao();Student student = new Student(null,"张三");//ID可以自增所以我们传nullStudent student2 = new Student(null,"王五");List<Student> studentList = new ArrayList<>();studentList.add(student);studentList.add(student2);//批量新增studentDao.insertInTx(studentList);
greenDao 还有一个方法 insertOrReplace 这个和 insert的使用方法是一样的,他是插入或替换数据,是根据主键来判断
studentDao.insertOrReplace(student);studentDao.insertOrReplaceInTx(studentList);
3 greenDao删除数据
studentDao.delete(student);//删除一个对象studentDao.deleteAll();//删除所有studentDao.deleteByKey(1l);//根据主键删除一条数据List<Long> idList = new ArrayList<>();studentDao.deleteByKeyInTx(idList);//根据主键删除列表studentDao.deleteInTx(studentList);//根据删除列表
4 greenDao 修改数据
//更新单条数据studentDao.update(student);//批量更新数据studentDao.updateInTx(studentList);
5 greenDao 查询数据
//查询所有List<Student> studentSearchList = studentDao.loadAll();studentSearchList = studentDao.queryBuilder().build().list();//查询数据共有多少条int count = (int) studentDao.count();count = (int) studentDao.queryBuilder().count();//更具条件查询数据//查询名字为张三的所有学生studentSearchList = studentDao.queryBuilder() .where(StudentDao.Properties.StudentName.eq("张三")) .build().list();//查询一个对象//查询Id是1的学生,id具有唯一性,所以查出来是单条数据Student student_1 = studentDao.queryBuilder() .where(StudentDao.Properties.Id.eq(1)) .build().unique();//多条件查询Student student_2 = studentDao.queryBuilder() .where(StudentDao.Properties.Id.eq(1),StudentDao.Properties.StudentName.eq("张三")) .build().unique();Student student_3 = studentDao.queryBuilder() .whereOr(StudentDao.Properties.Id.eq(1),StudentDao.Properties.StudentName.eq("张三")) .build().unique();/** * greenDao判断条件 * * eq 等于 * notEq 不等于 * like 模糊查询 * between 介于。。。之间 * in 包含 可以是一属性,也可以是集合 * notIn 不包含 可以是一属性,也可以是集合 * gt 大于 * ge 大于等于 * lt 小于 * le 小于等于 * isNull 为null * isNotNull 不为null *//** * greenDao 排序 * * orderAsc 升序 * orderDesc 降序 * and /or */
where 和 whereOr 后面可以跟多个条件
模糊查询
// 模糊查询 studentSearchList = studentDao.queryBuilder() .where(StudentDao.Properties.StudentName.like("%张%"))//名字中包含张的学生 .build().list();
数据排序
//查询数据排序 升序studentSearchList = studentDao.queryBuilder() .orderAsc(StudentDao.Properties.Id) .build().list();/** * greenDao 排序 * * orderAsc 升序 * orderDesc 降序 */
分页查询
注意page是从0开始的
// 分页查询 int page = 0;//注意page是从0开始的 studentSearchList= studentDao.queryBuilder().offset(page * 20).limit(20).list();
Over!
如有不明白的可以观看视频
https://www.bilibili.com/video/BV1Qt4y117Up
更多相关文章
- 详解如何让Android(安卓)UI设计性能更高效
- 原:Android(安卓)获取屏幕高度、标题高度、状态栏高度详解
- Android的IPC方式
- Android(安卓)Vold实现总览
- Android性能测试(内存、cpu、fps、流量、GPU、电量)——adb篇
- Android练手小项目(KTReader)基于mvp架构(二)
- android Content Provider的使用
- SQlite字段类型升级
- Android(安卓)TTS学习——TTS初体验