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

  • 相关阅读:
    win10快速搭建git服务
    java字节流转对象,应用于协议解析
    产品设计-后台管理权限设计RBAC
    Git :fatal: 错误提示解决办法
    初学git,出现错误:fatal: Not a git repository (or any of the parent directories): .git
    css 清除浮动
    asp.net连接SQL SERVER 2012的方法
    c#的序列化与反序列化
    .NET三层架构例子超链接可以点击显示内容页面
    ASP.NET中iframe框架点击左边页面链接,右边显示链接页面内容
  • 原文地址:https://www.cnblogs.com/milovetingting/p/12715506.html
Copyright © 2011-2022 走看看