我想将这些实体插入数据库: 看来我无法正确构建嵌套实体。我需要你的帮助
[1] 文章实体
@Entity(
tableName = "articles",
foreignKeys = [
ForeignKey(
entity = PartCargo::class,
parentColumns = ["tId"],
childColumns = ["partTId"],
onDelete = ForeignKey.CASCADE
)
]
)
data class ArticleEntity(
@PrimaryKey(autoGenerate = true)
val tId: Long = 0,
val partTId: Long = -1,
val id: String?,
val name: String?,
) : Serializable
[2] 部分实体
@Entity(
tableName = "parts",
foreignKeys = [
ForeignKey(
entity = DetailsCargo::class,
parentColumns = ["tId"],
childColumns = ["detailsTId"],
onDelete = ForeignKey.CASCADE
)
]
)
data class PartCargo(
@PrimaryKey(autoGenerate = true)
val tId: Long = 0,
val detailsTId: Long = -1,
val id: String?,
val name: String?,
) : Serializable
data class PartEntity(
@Embedded
val part: PartCargo,
@Relation(parentColumn = "tId", entityColumn = "partTId")
val partArticles: List<ArticleEntity>?
) : Serializable
[3] 详情实体
@Entity(tableName = "details")
data class DetailsCargo(
@PrimaryKey(autoGenerate = true)
val tId: Long = 0,
val id: String?,
val name: String?
) : Serializable
data class DetailsEntity(
@Embedded
val details: DetailsCargo,
@Relation(parentColumn = "tId", entityColumn = "detailsTId")
val parts: List<PartEntity>?
) : Serializable
这是详情DAO
@Dao
interface DetailsDAO {
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertPartCargo(parent: PartCargo): Long
@Transaction
fun insertAllParts(parentId: Long, parts: List<PartEntity>) {
parts.forEach { part ->
val cargoParentId = insertPartCargo(part.part.copy(detailsTId = parentId))
part.partArticles?.let { items ->
val children = items.map { it.copy(partTId = cargoParentId) }
insertArticleEntities(children)
}
}
}
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertDetailsCargo(parent: DetailsCargo): Long
@Transaction
fun insertDetails(details: DetailsEntity) {
val parentId = insertDetailsCargo(details.details)
details.parts?.let { items ->
insertAllParts(parentId, items)
}
}
@Transaction
@Query("SELECT * FROM details WHERE :id = id")
fun getDetails(id: String): DetailsEntity?
}
现在,我在构建应用程序时遇到此错误:
Cannot find the child entity column `detailsTId` in PartEntity.
提前致谢
未完全检查关系,但如果您使用分层(嵌套),则较低的
@Relation
注释应反映实体(列所在的表)而不是 POJO。
@Relation
有一个实体参数,应该使用它,因此我相信您的问题可以通过使用来解决:-
data class DetailsEntity(
@Embedded
val details: DetailsCargo,
@Relation(entity = PartCargo::class, parentColumn = "tId", entityColumn = "detailsTId")
val parts: List<PartEntity>?
) : Serializable
没有(注释掉)则:-
与:-
您可能希望留意 3 条警告并在相应字段上使用
@ColumnInfo
,例如
....
@ColumnInfo(index = true)
val partTId: Long = -1,
....