Android Jetpack组件-Room简单使用

这是我参与 8 月更文挑战的第 11 天,活动详情查看: 8月更文挑战

背景

在项目中不可避免的使用数据库, 而三方框架又是五花八门, 在这中我就选择了google Jetpack组件中的Room

集成

详情请参见google官方集成文档
在bulid中引用对应的主要jar包

implementation 'androidx.room:room-runtime:2.2.5'
annotationProcessor 'androidx.room:room-compiler:2.2.5'
复制代码

可选jar包如下:

$room_version 我在项目中用的是2.2.5, 请以最新的为主

    // optional - RxJava2 support for Room
    implementation "androidx.room:room-rxjava2:$room_version"

    // optional - RxJava3 support for Room
    implementation "androidx.room:room-rxjava3:$room_version"

    // optional - Guava support for Room, including Optional and ListenableFuture
    implementation "androidx.room:room-guava:$room_version"

    // optional - Test helpers
    testImplementation "androidx.room:room-testing:$room_version"

    // optional - Paging 3 Integration
    implementation "androidx.room:room-paging:2.4.0-alpha04"
复制代码

配置编译器选项

includeCompileClasspath启用 Gradle 增量注解处理器。
room.schemaLocation配置并启用将数据库架构导出到给定目录中的 JSON 文件的功能。

javaCompileOptions {
    annotationProcessorOptions {
        includeCompileClasspath = true
        arguments = ["room.schemaLocation":
                              "$projectDir/schemas".toString()]
    }
}
复制代码

创建数据库

  • 继承RoomDatabase 并通过Room.databaseBuilder创建对象

在通过build方式创建AppDatabase对象时可以使用allowMainThreadQueries设置对DB的操作是否在主线程,使用addMigrations方法设置数据库升级兼容

public static void init(final Context context) {
    if (sInstance == null) {
        synchronized (AppDatabase.class) {
            if (sInstance == null) {
                sInstance = buildDB(context);
            }
        }
    }
}

private static AppDatabase buildDB(Context context) {
    return Room.databaseBuilder(context, AppDatabase.class, DATABASE_NAME)
            .allowMainThreadQueries()
            .build();
}
复制代码
  • 在自定义的ApplicationonCreate方法中调用init方法
AppDatabase.init(this);
复制代码

创建表

  • 使用@Entity注解定义的类会被映射为数据库中的一张表,默认实体类的类名为表名,可以通过tableName字段指定表名,例如:
@Entity(tableName = "Test")
public class TestEntity {
}
复制代码
  • AppDatabase类中使用@Database注解关联数据表并指定数据库版本, 这样在初始化AppDatabase类时就会自动创建数据库和数据表
@Database(entities = {TestEntity.class},version = 1)
public abstract class AppDatabase extends RoomDatabase {
}
复制代码

添加字段

  • 通过@PrimaryKey注解进行指定主键
  • 通过@NonNull注解指定当前字段不可为空
  • 通过@ColumnInfo注解指定当前字段对应的数据表字段
@NonNull
@PrimaryKey
@ColumnInfo(name = "dataID")
private String dataID;
复制代码

如果数据表实体类和解析服务器返回字段几乎一致, 以Gson为例, 可选择使用@SerializedName注解对字段进行容错处理, 既@ColumnInfo注解指定数据表字段,@SerializedName注解指定解析json格式对应的key

示例

@ColumnInfo(name = "changeType")
@SerializedName(value = "ChangeType")
private int changeType;
复制代码
  • 忽略实体类中的某一字段

通过@Ignore注解进行实现, @Ignore注解标注的字段不会被处理成数据表字段

@Ignore
private String test;
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享