Android - room 入門

主要由Entity、DAO、RoomDatabase組成

Entity

@Entity(tableName = "users")
class User(
    @PrimaryKey(autoGenerate = true) val id:Int,
    @ColumnInfo(name = "name") val name:String,
    @ColumnInfo(name = "mobile") val mobile:String,
    @ColumnInfo(name="address") val address:String
)
DAO

@Dao
interface UserDao {
    @Query("SELECT * from users ORDER BY id ASC")
    fun getALL(): LiveData<List<User>>

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    fun insert(user:User)

    @Query("DELETE FROM users")
    fun deleteAll()
}
RoomDatabase

@Database(entities = arrayOf(User::class), version = 3, exportSchema = false)
abstract class UserRoomDatabase : RoomDatabase() {
    abstract fun userDao(): UserDao

    companion object {
        @Volatile
        private var INSTANCE: UserRoomDatabase? = null
        fun getDataBase(context: Context): UserRoomDatabase {
            val tempInstance = INSTANCE
            if (tempInstance != null) {
                return tempInstance
            }
            synchronized(this) {
                val instance = Room.databaseBuilder(
                    context.applicationContext, UserRoomDatabase::class.java,
                    "users"
                )
                    .addMigrations(MIGRATION_1_2)
                    .addMigrations(MIGRATION_2_3)
                    .build()
                INSTANCE = instance
                return instance
            }
        }
        //如果有新增欄位一定要好好寫描述,然後還要加上not null & default value
        val MIGRATION_1_2: Migration = object : Migration(1, 2) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL("ALTER TABLE users ADD COLUMN mobile TEXT NOT NULL DEFAULT ''")
            }
        }
        val MIGRATION_2_3: Migration = object : Migration(2, 3) {
            override fun migrate(database: SupportSQLiteDatabase) {
                database.execSQL("ALTER TABLE users ADD COLUMN address TEXT NOT NULL DEFAULT ''")
            }
        }
    }
}

不能在主執行緒跑

AsyncTask.execute {
    val dao = UserRoomDatabase.getDataBase(this).userDao()
    dao.insert(User(id = 0, name = "123",mobile = "99999",address = "66666"))
}