个人博客
Jetpack学习-Room
Room是什么
Room 持久性库在 SQLite 的基础上提供了一个抽象层,让用户能够在充分利用 SQLite 的强大功能的同时,获享更强健的数据库访问机制
以上内容来自官方文档。用一句话总结下:Room是基于SQLite封装的一个框架。
简单使用
引入Room
在需要使用的模块的build.gradle中增加以下配置:
dependencies {
//...
def room_version = "2.2.3"
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"
}
room_version
最新可用的版本可以在官方的文档上查看。
Entity
//@Entity标识这个类用于建表
@Entity
public class Student {
//@PrimaryKey:主键,autoGenerate:是否自增长
@PrimaryKey(autoGenerate = true)
public int id;
//@ColumnInfo:表中的字段,name:表中的字段名
@ColumnInfo(name = "name")
public String name;
//@ColumnInfo:表中的字段,默认用下面的字段名age
@ColumnInfo
public int age;
}
Dao
@Dao
public interface StudentDao {
@Insert
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);
}
通过@Dao
来标识这是一个Dao,在编译时会通过APT
生成具体的实现类。@Insert
,@Delete
,@Update
,@Query
同理。
DataBase
@Database(entities = {Student.class}, version = 1)
public abstract class DataBase extends RoomDatabase {
public abstract StudentDao studentDao();
}
使用
DataBase dataBase = Room.databaseBuilder(getApplicationContext(), DataBase.class, "room").build();
StudentDao dao = dataBase.studentDao();
List<Student> students = dao.getAll();
以上只介绍了最基本的使用步骤,有关数据库升级
、多表关联
,查询部分字段
等,可以在官方文档上查看。
原理
上面使用的过程中,大量用到了注解,可以推测出,Room是通过注解处理器来辅助生成所需要的类文件,具体原理这里不再展开,还是比较简单的(其实是我不想写_)。
网友评论