[英]Android Room Embedded Field Not Compiling
我正在嘗試創建一個嵌入式字段。 這是一個簡單的例子,但我無法讓這個簡單的例子工作。 最終我需要有 3 個級別的嵌入項目,但試圖讓這個測試用例工作。
@Entity(tableName = "userItemsEntity")
@Parcelize
data class Item(
var objecttype: String?,
@PrimaryKey(autoGenerate = false)
var objectid: Int?,
var subtype: String?,
var collid: Int?,
@Embedded
var name: Name?
) : Parcelable
@Parcelize
data class Name(
var primary: Boolean? = true,
var sortindex: Int? = null,
var content: String? = null) : Parcelable
當我嘗試編譯它時,它在 DAO 上抱怨 updateItem()
SQL error or missing database (no such column: name)
DAO函數
@Query("UPDATE userItemsEntity SET " +
"objecttype=:objecttype, objectid=:objectid, subtype=:subtype, collid=:collid, name=:name " +
"WHERE objectid=:objectid")
fun updateItem(
objecttype: String?,
objectid: Int,
subtype: String?,
collid: Int?,
name: Name?)
原因是因為它說沒有名稱列。 相反,該表由列組成,根據 EMBEDDED 類的成員變量(即主要、排序索引和內容)。
即表創建 SQL 是/將是:-
CREATE TABLE IF NOT EXISTS `userItemsEntity` (`objecttype` TEXT, `objectid` INTEGER, `subtype` TEXT, `collid` INTEGER, `primary` INTEGER, `sortindex` INTEGER, `content` TEXT, PRIMARY KEY(`objectid`))
Room 知道在提取行時從這些列構建各自的Name對象。
所以你可以使用:-
@Query("UPDATE userItemsEntity SET " +
"objecttype=:objecttype, objectid=:objectid, subtype=:subtype, collid=:collid, `primary`=:primary, sortindex=:sortindex, content=:content " +
"WHERE objectid=:objectid")
fun updateItem(
objecttype: String?,
objectid: Int,
subtype: String?,
collid: Int?,
primary: Boolean?,
sortindex: Int?,
content: String?
)
請注意,primary 是一個 SQLite 標記,因此用重音符括起來以確保它不被視為標記。 否則你會得到:-
There is a problem with the query: [SQLITE_ERROR] SQL error or missing database (near "primary": syntax error)
但是,當您使用基於主鍵 (objectid) 的 WHERE 子句時,更新將僅適用於單行,因此您可以簡單地使用:-
@Update
fun update(item: Item): Int
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.