Jetpack学习-Room

个人博客

http://www.milovetingting.cn

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是通过注解处理器来辅助生成所需要的类文件,具体原理这里不再展开,还是比较简单的(其实是我不想写_)。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值