Room是android的一个持久化库,SQLite的抽象层,便于使用。推荐用Room替代SQLite。
[TOC]
引入room库
在project的gradle中加入google仓库
1 | allprojects { |
在app的gradle中加入room依赖
其中最后3个是用来支持rxjava2的,方便使用
1 | dependencies { |
初始化
在Application
中初始化数据库,记得在AndroidManifest.xml
中配置App
1 | public class App extends Application { |
Room的3大组件
- Database 数据库
- Entity 实体类
- DAO 数据访问对象
概念不是很难,直接看代码更加方便
1 | 1) // 数据库注解,必须。entities指定实体类,version指定数据库版本 (entities = {Student.class}, version = |
1 | // 实体类注解,必须 |
1 |
|
数据访问(增删查改)
Insert
1 | Student s = new Student(); |
Delete
1 | final Student s = studentList.get(position); |
Select
1 | App.getDb().studentDao().getAll() |
Update
1 | Action action = () -> { |
到这里,我们已经可以简单的增删查改数据库了。
注意事项
遇到下面的这个警告,说的是找不到地方导出schema
1 | 警告: Schema export directory is not provided to the annotation processor so we cannot export the schema. You can either provide `room.schemaLocation` annotation processor argument OR set exportSchema to false. |
解决方案
在app的gradle文件中添加
1 | android { |