Room是什么
持久性库在SQLite基础上提供抽象层,充分利用SQLite强大功能,更强的数据库访问机制。
Room是基于SQLite封装的一个框架。
简单使用
引入room,模块build.gradle增加配置
dependencies {
...
implementation 'androidx.room:room-runtime:2.2.5'
annotationProcessor 'androidx.room:room-compiler:2.2.5'
}
Entity
// @Entity 标识这个类用于建表,表名(默认不写,则用类名小写作为表名)
@Entity(tableName = "student")
public class Student {
// 主键,是否自增长
@PrimaryKey(autoGenerate = true)
public int id;
// 表中字段,表中字段名
@ColumnInfo(name = "name")
public String name;
// 表中字段,默认使用下面字段名age
@ColumnInfo
public int age;
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
Dao
@Dao
public interface StudentDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insert(Student... students);
@Delete
void delete(Student student);
@Update
void update(Student student);
@Query("SELECT * FROM student")
List<Student> getAll();
@Query("SELECT * FROM student WHERE name = :name")
List<Student> findByName(String name);
@Query("SELECT * FROM student WHERE id in (:ids)")
List<Student> findByIds(int[] ids);
}
DataBase
@Database(entities = {Student.class},version = 1)
public abstract class DataBase extends RoomDatabase {
public abstract StudentDao studentDao();
}
使用
public class RoomActivity extends AppCompatActivity {
private static final String TAG = "Room-";
private StudentDao dao;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_room);
DataBase dataBase = Room.databaseBuilder(getApplicationContext(), DataBase.class,
"room").allowMainThreadQueries().build();
dao = dataBase.studentDao();
String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(permissions, 1);
}
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == 1) {
Log.d(TAG, "onRequestPermissionsResult: " + requestCode);
for (int i = 0; i < grantResults.length; i++) {
if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "onRequestPermissionsResult-需要开启存储权限");
}
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
/**
* 在Activity中所有对数据库的操作(增、删、改、查)都不可以在主线程中进行,除非在数据库的Builder上调用了allowMainThreadQueries(),
* 或者所有的操作都在子线程中完成,否则程序会崩溃报以下错误
* Cannot access database on the main thread since it may potentially lock the UI for a long period of time.
*
* @param view
*/
public void queryAll(View view) {
List<Student> students = dao.getAll();
Log.d(TAG, "queryAll: " + students);
}
public void insert(View view) {
Student student = new Student();
student.age = 18;
student.name = "小明";
dao.insert(student);
Log.d(TAG, "insert:" + student.toString());
}
/**
* 删除必须指定id,否则删除不成功(id不存在也是删除不成功的)
*
* @param view
*/
public void delete(View view) {
Student student = new Student();
student.age = 18;
student.name = "小明";
student.id = 1;
dao.delete(student);
Log.d(TAG, "insert:" + student.toString());
}
/**
* 更新必须指定id,否则不成功(id不存在也是更新不成功的)
*
* @param view
*/
public void update(View view) {
Student student = new Student();
student.age = 18;
student.name = "小明-1";
student.id = 1;
dao.update(student);
Log.d(TAG, "insert:" + student.toString());
}
public void queryByName(View view) {
Log.d(TAG, "queryByName: " + dao.findByName("小明"));
}
public void queryByIds(View view) {
Log.d(TAG, "queryByName: " + dao.findByIds(new int[]{1, 2, 3}));
}
}
当然这是基础用法,有关数据库升级、多表关联、查询部分字段等随后写。
数据库信息导出
允许表信息导出json文件。应该在版本控制中保存该文件,代表数据库历史,允许创建就版本数据库用于测试。配置如下build.gradle
android{
defaultConfig {
···
javaCompileOptions {
annotationProcessorOptions {
arguments = ["room.schemaLocation":
"$projectDir/schemas".toString()]
}
}
}
// 用于测试
sourceSets {
androidTest.assets.srcDirs += files("$projectDir/schemas".toString())
}
}
schemas路径:项目名/app/schemas
image.png
{
"formatVersion": 1,
"database": {
"version": 1,
"identityHash": "acca4b709e6c8b9b88d8328be36b9032",
"entities": [
{
"tableName": "student",
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT, `age` INTEGER NOT NULL)",
"fields": [
{
"fieldPath": "id",
"columnName": "id",
"affinity": "INTEGER",
"notNull": true
},
{
"fieldPath": "name",
"columnName": "name",
"affinity": "TEXT",
"notNull": false
},
{
"fieldPath": "age",
"columnName": "age",
"affinity": "INTEGER",
"notNull": true
}
],
"primaryKey": {
"columnNames": [
"id"
],
"autoGenerate": true
},
"indices": [],
"foreignKeys": []
}
],
"views": [],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'acca4b709e6c8b9b88d8328be36b9032')"
]
}
}
原理
大量用了注解,Room是根据注解处理器辅助生成类文件。
网友评论