先上
Entity
@Entity(tableName = "AppDataBase")
data class Entity constructor(@ColumnInfo(name = "id")
@PrimaryKey(autoGenerate = true)
var id: Int = 0,
@ColumnInfo(name = "name")
var name: String? = null
) {
constructor() : this(0)
}
DAO
@Dao
interface KotlinDao {
@Insert
fun insertKotlin(kotlin: Entity)
@Insert
fun insertKotlins(kotlins: List<Entity>)
@Query("select * from kotlin")
fun selectKotlin(): List<Entity>
}
如上設定,如果要新增資料時,會使用到data class Entity。
但是,我們在Entity裡設定id為autoGenerate = true,
所以要新增時,每次都要取得之前資料的最後一筆才能執行動作,不然會報錯。
這時候可以使用一種方法,首先改寫Entity
@Entity(tableName = "AppDataBase")
data class Entity constructor(@ColumnInfo(name = "id")
@PrimaryKey(autoGenerate = true)
var id: Int? = 0,
@ColumnInfo(name = "name")
var name: String? = null
) {
constructor() : this(0)
}
將帶有宣告為autoGenerate = true的欄位,宣告成可空型態。
這邊的例子是把var id: Int = 0改成var id: Int? = 0
在Activity將id的值改成null。
...
var list: List<Entity> = emptyList()
list += Entity(id = null, name = "I am one")
list += Entity(id = null, name = "I am two")
list += Entity(id = null, name = "I am three")
list += Entity(id = null, name = "I am four")
list += Entity(id = null, name = "I am five")
appDb.kotlinDao().insertKotlins(list)
...
這樣在新增時,由於我們指定null值給id,故每筆新增資料autoGenerate就會自動補上最新遞增數值。