当在Room中进行多次跨引用或计数交叉引用时,可以使用以下代码示例来避免重复引用。
假设我们有两个实体,User和Task,Task包含对User的引用:
@Entity(tableName = "users") data class User( @PrimaryKey val userId: String, val name: String )
@Entity( tableName = "tasks", foreignKeys = [ForeignKey(entity = User::class, parentColumns = ["userId"], childColumns = ["userId"], onDelete = ForeignKey.CASCADE)] ) data class Task( @PrimaryKey val taskId: String, @ColumnInfo(index = true) val userId: String, val description: String )
然后我们需要一个包含有多个Task的User的数据类:
data class UserWithTasks(
@Embedded val user: User,
@Relation(
parentColumn = "userId",
entityColumn = "userId"
)
val tasks: List
但是,如果我们需要在上面的模型中再次引用UserWithTasks,例如,将其用作一个新的实体的属性:
@Entity data class Project( @PrimaryKey val projectId: String, val name: String, // Duplicate reference to UserWithTasks @Embedded val userWithTasks: UserWithTasks )
使用@Ignore注解,我们可以避免重复引用并保持代码简短:
@Entity
data class Project(
@PrimaryKey val projectId: String,
val name: String,
@Ignore
val user: User,
@Relation(
parentColumn = "userId",
entityColumn = "userId"
)
val tasks: List
我们仍然可以使用UserWithTasks数据类,但是现在它既包含User和List