Android Room 数据库使用详解

一、Room介绍

Android Room 是 Google 提供的一个 Android 数据持久化库,是 Android Jetpack 组成部分之一。它提供了一个抽象层,使得 SQLite 数据库的使用更为便捷。通过 Room,开发者可以轻松地操作数据库,不需要直接编写繁琐的 SQL 语句。

Room官方使用示例:https://developer.android.google.cn/codelabs/android-room-with-a-view-kotlin?hl=zh-cn#0

Room 包含三个主要组件

  • 数据库类,用于保存数据库并作为应用持久性数据底层连接的主要访问点。
  • 数据实体类,用于表示应用的数据库中的表。
  • 数据访问对象 (DAO),为您的应用提供在数据库中查询、更新、插入和删除数据的方法。

数据库类为应用提供与该数据库关联的 DAO 的实例。反过来,应用可以使用 DAO 从数据库中检索数据,作为关联的数据实体对象的实例。此外,应用还可以使用定义的数据实体更新相应表中的行,或者创建新行供插入。图 1 说明了 Room 的不同组件之间的关系。

二、引入Room库

在build.gradle中引入Room库:

复制代码
    //Room数据库
    def room_version = "2.5.1"
    implementation "androidx.room:room-runtime:$room_version"
    annotationProcessor "androidx.room:room-compiler:$room_version"

三、创建实体类

复制代码
//实体类 表名 不写默认类名首字母小写
@Entity(tableName = "student")
public class StudentEntity {
    //主键 自动生成
    @PrimaryKey(autoGenerate = true)
    private int id;

    private String name;

    private int age;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

四、创建数据访问对象 (DAO)

复制代码
@Dao
public interface StudentDao {

    //插入采集信息
    @Insert
    void insert(StudentDao studentDao);

    //删除
    @Delete
    void delete(StudentDao studentDao);

    //更新
    @Update
    void update(StudentDao studentDao);

    //查询 名称查询 
    @Query("select * from student where name =:studentName LIMIT 1")
    CollectEntity getCollectEntityByFileName(String studentName);

    //查询 根据age倒序
    @Query("select * from student order by age desc")
    List<CollectEntity> getAllCollectList();

    /**
     * 查询 根据age倒序,分页查询
     *
     * @param pageSize  每页的数据量
     * @param offset 偏移量
     */
    @Query("select * from student order by age desc LIMIT :pageSize OFFSET :offset")
    List<CollectEntity> getPageCollectList(int pageSize, int offset);
}

五、创建数据库类

复制代码
@Database(entities = {StudentEntity.class}, version = 1)
public abstract class AppDatabase extends RoomDatabase {
    public static volatile AppDatabase instance;

    public abstract StudentDao studentDao();

    public static AppDatabase getInstance() {
        if (instance == null) {
            synchronized (AppDatabase.class) {
                if (instance == null) {
                    instance = Room.databaseBuilder(Utils.getApp().getApplicationContext(),
                                    AppDatabase.class, testDb)
                            //是否允许在主线程上操作数据库,默认false。
                            .allowMainThreadQueries()
                            .build();
                }
            }
        }
        return instance;
    }
}

六、使用数据库

复制代码
   StudentDao studentDao = AppDatabase.getInstance().studentDao();
   studentDao.insert(studentEntity);

七、更新数据库

将age的属性由int 更改为 String,version 版本号加1

复制代码
@Database(entities = {StudentEntity.class}, version = 2)
public abstract class AppDatabase extends RoomDatabase {
    public static volatile AppDatabase instance;

    public abstract StudentDao studentDao();

    public static AppDatabase getInstance() {
        if (instance == null) {
            synchronized (AppDatabase.class) {
                if (instance == null) {
                    instance = Room.databaseBuilder(Utils.getApp().getApplicationContext(),
                                    AppDatabase.class, QZConstants.DB.DB_NAME)
                            //是否允许在主线程上操作数据库,默认false。
                            .allowMainThreadQueries()
                            .addMigrations(MIGRATION_1_2)
                            .build();
                }
            }
        }
        return instance;
    }

    private static final Migration MIGRATION_1_2 = new Migration(1, 2) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            //创建一个新表,表名为students,age属性为String 
            database.execSQL("CREATE TABLE IF NOT EXISTS students(id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, name TEXT, age TEXT)");
            //将旧表student表中的数据迁移到新表students
            database.execSQL("insert into students(id, name, age) select id, name, age from student");
            //删除旧表student
            database.execSQL("drop table student");
            //将新表students名称修改为student
            database.execSQL("alter table students rename to student");
        }
    };  

}

升级数据库:https://blog.51cto.com/u_14152/9288966

相关推荐
←か淡定☆ ヾ18 分钟前
SQL Server 2008R2 到 2012 数据库迁移完整指南
数据库·sql server
瀚高PG实验室24 分钟前
Arcgis连接HGDB报错
数据库·arcgis·瀚高数据库
感觉不怎么会1 小时前
Android 12 - 部分相机横屏显示方案
android
IT小辉同学1 小时前
PostgreSQL 与 MySQL 获取字段注释并转换为驼峰命名教程
数据库·mysql·postgresql
xinghunzhiye20101 小时前
redis升级
数据库·redis·缓存
一只fish2 小时前
MySQL 8.0 OCP 1Z0-908 题目解析(21)
数据库·mysql
涛思数据(TDengine)2 小时前
时序数据库 TDengine × SSRS:专为工业、能源场景打造的报表解决方案
大数据·数据库·物联网·时序数据库·tdengine
打鱼又晒网2 小时前
Lecture #20:Database Logging
数据库
白仑色2 小时前
Oracle 数据库管理与维护实战指南(用户权限、备份恢复、性能调优)
数据库·oracle·数据库管理·性能调优·备份恢复
wx_ywyy67982 小时前
分布式推客系统全栈开发指南:SpringCloud+Neo4j+Redis实战解析
数据库·oracle·推客系统·推客小程序·推客系统开发·推客小程序开发·推客分销系统