# Room
一个来自Android 开发者官方JetPack的SqLite类库 用来存储 查询 sql数据非常简单...
# 先来看看如何导入Room
apply from: 'versions.gradle' buildscript { ext.kotlin_version = '1.3.31' repositories { google() jcenter() } dependencies { classpath 'com.android.tools.build:gradle:3.4.1' classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { google() jcenter() } } task clean(type: Delete) { delete rootProject.buildDir }复制代码
app/build.gradle 下 设置
dependencies { def dep = rootProject.ext.dep implementation fileTree(dir: 'libs', include: ['*.jar']) implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" implementation dep.x_appcompat implementation dep.x_room implementation dep.gson kapt dep.x_room_compiler // kapt kotlin 注解处理器 implementation 'androidx.core:core-ktx:1.0.2' testImplementation dep.junit annotationProcessor dep.x_room_compiler androidTestImplementation dep.x_android_test_runner androidTestImplementation dep.x_android_test_espresso}复制代码
def dep = [:]def version = [:]version.x_appcompat = "1.0.2"version.junit = "4.12"version.x_android_test_runner = "1.1.1"version.x_android_test_espresso = "3.1.1"version.gson = "2.8.2"version.x_room = "2.1.0-beta01"dep.x_appcompat = "androidx.appcompat:appcompat:$version.x_appcompat"dep.junit = "junit:junit:$version.junit"dep.x_android_test_runner = "androidx.test:runner:$version.x_android_test_runner"dep.x_android_test_espresso = "androidx.test.espresso:espresso-core:3.1.1"dep.gson = "com.google.code.gson:gson:$version.gson"dep.x_room = "androidx.room:room-runtime:$version.x_room"dep.x_room_compiler = "androidx.room:room-compiler:2.1.0-alpha04"复制代码
# Room 常用的注解
- @Entity(tableName="xxx")
表注解
- @PrimaryKey
主键
主键不能为空 - @ColumnInfo(name="xxxx")
列名注解
- @Dao
Sql 操作接口注解
- @TypeConverters
类型转换器
Room 实体类存储List 会报错:
Cannot figure out how to save this field into database. You can consider adding a type converter for it.
// example converter for java.util.Date public static class Converters { @TypeConverter public Date fromTimestamp(Long value) { return value == null ? null : new Date(value); } @TypeConverter public Long dateToTimestamp(Date date) { if (date == null) { return null; } else { return date.getTime(); } }}复制代码
# 创建表
@Entity(tableName = "class_cache")@TypeConverters(UserConverters::class)data class ClassCache( @PrimaryKey val id: String, @ColumnInfo(name = "class_name") val className: String?, @ColumnInfo(name = "grade") val grade: String?, @ColumnInfo(name = "users") val users: List)@Entity(tableName = "user_cache", primaryKeys = ["user_id", "class_id"])data class UserCache( @ColumnInfo(name = "user_id") val userId: String, @ColumnInfo(name = "class_id") val classId: String, @ColumnInfo(name = "user_name") val userName: String?, @ColumnInfo(name = "sex") val sex: Int)/** * 类型转换器 */class UserConverters { @TypeConverter fun stringToObject(value: String): List { val listType = object : TypeToken
>() { }.type return Gson().fromJson(value, listType) } @TypeConverter fun objectToString(list: List ): String { val gson = Gson() return gson.toJson(list) }}复制代码
# 创建接口
@Daointerface ClassDao { @Query("select * from class_cache") fun getAllClass(): List@Query("select * from class_cache where id=:classId") fun getClass(classId: String): ClassCache @Insert fun insertClass(classList: List ) @Insert fun insertClassOne(classCache: ClassCache) @Delete fun delClassCache(classList: List ) @Delete fun delClassOne(classCache: ClassCache)}复制代码
# 数据库
@Database(entities = arrayOf(ClassCache::class, UserCache::class), version = 1)abstract class AppDatabase : RoomDatabase() { abstract fun getClassDao(): ClassDao companion object { // For Singleton instantiation @Volatile private var instance: AppDatabase? = null fun getInstance(context: Context): AppDatabase { return instance ?: synchronized(this) { instance ?: buildDatabase(context).also { instance = it } } } private fun buildDatabase(context: Context): AppDatabase { return Room.databaseBuilder(context, AppDatabase::class.java, "test-db") .allowMainThreadQueries()//允许在主线程查询数据 .addMigrations()//迁移数据库使用 .fallbackToDestructiveMigration()//迁移数据库如果发生错误,将会重新创建数据库,而不是发生崩溃 .build() } }复制代码
# 数据库升级 Migrations
//数据库升级 迁移 object Migrations { // val MIGRATION_1_2 = object : Migration(1, 2) { // override fun migrate(database: SupportSQLiteDatabase) { // database.execSQL( // "CREATE TABLE `Fruit` (`id` INTEGER, `name` TEXT, " + // "PRIMARY KEY(`id`))" // ) // } // } }复制代码