博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Android JetPack Library Room
阅读量:5933 次
发布时间:2019-06-19

本文共 5494 字,大约阅读时间需要 18 分钟。

# 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`))" // ) // } // } }复制代码

转载于:https://juejin.im/post/5d030fc7e51d4577555508bd

你可能感兴趣的文章
C#用odp.net连接Oracle 数据库
查看>>
#!/usr/bin/python3的作用 解决vscode ImportError: No module named xxxx
查看>>
Koa2学习记录
查看>>
svn 新建用户,删除用户,更改用户密码
查看>>
替换字符串中空格为”%20“
查看>>
Android RecyclerView 使用完全解析 体验艺术般的控件
查看>>
Linux 脚本语言入门
查看>>
C errors recods
查看>>
linux内核编译
查看>>
dubbo学习笔记四(异步调用)
查看>>
语言代码表
查看>>
IOS数据存储-NSUserDefaults
查看>>
NDK 编译问题 总结
查看>>
复习日记-SQL+连接池
查看>>
hdu 1007 Quoit Design
查看>>
织梦(dedecms)如何清空全部文章和删除后新增文章id号归1的方法
查看>>
认识EasyUI——DataGrid的onClickRow事件
查看>>
Android Studio的使用(四)--生成Get、Set方法
查看>>
删除底部"自豪地采用 WordPress"
查看>>
i897刷机原理分析
查看>>