Android JetPack Library Room

# Room

一個來自Android 開發者官方JetPack的SqLite類庫 用來存儲 查詢 sql數據很是簡單...html

AndroidDevelopers: Roomjava

# 先來看看如何導入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 下 設置android

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.sql

官方提供類@TypeConverter 轉換器數據庫

// 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<UserCache>
)

@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<UserCache> {
        val listType = object : TypeToken<List<UserCache>>() {

        }.type
        return Gson().fromJson(value, listType)
    }

    @TypeConverter
    fun objectToString(list: List<UserCache>): String {
        val gson = Gson()
        return gson.toJson(list)
    }
}
複製代碼

# 建立接口

@Dao
interface ClassDao {

    @Query("select * from class_cache")
    fun getAllClass(): List<ClassCache>

    @Query("select * from class_cache where id=:classId")
    fun getClass(classId: String): ClassCache

    @Insert
    fun insertClass(classList: List<ClassCache>)

    @Insert
    fun insertClassOne(classCache: ClassCache)

    @Delete
    fun delClassCache(classList: List<ClassCache>)

    @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`))"
        // )
        // }
        // }
    }
複製代碼
相關文章
相關標籤/搜索