我使用房间数据库(多对多关系)。我试着把演员名单保存到一个表中。但是数据库发现我插入了具有相同id(电影id)的cast,并重写了该值。你知道怎么改正吗?
我在以下查询的帮助下插入一个列表:
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertCast (cast: List <CastDbModel>)
但当我尝试获取数据时,我得到了插入的最后一个数据。
@Transaction
@Query("select * FROM `cast` WHERE id = :id")
fun getAllCastAssociatedWithMovie(id: Int): List<CastDbModel>
@Entity(tableName = "movie")
data class MovieDbModel(
@PrimaryKey(autoGenerate = false)
val id: Int,
val poster_path: String,
val overview: String,
val title: String)
@Entity(tableName = "cast")
@TypeConverters(CastConverter::class)
data class CastDbModel(
@PrimaryKey(autoGenerate = false)
val id : Int,
val cast: Cast
)
data class Cast(
val name: String,
val profile_path: String?,
val character: String
)
data class MovieWithListOfCast(
@Embedded /* The parent */
val movie: CastDbModel,
@Relation(
entity = CastDbModel::class, /* The class of the related table(entity) (the children)*/
parentColumn = "id", /* The column in the @Embedded class (parent) that is referenced/mapped to */
entityColumn = "id", /* The column in the @Relation class (child) that is referenced (many-many) or references the parent (one(parent)-many(children)) */
/* For the mapping table */
associateBy = Junction(
value = MovieCastCrossRef::class, /* The class of the mapping table */
parentColumn = "movieIdMap", /* the column in the mapping table that maps/references the parent (@Embedded) */
entityColumn = "castIdMap" /* the column in the mapping table that maps/references the child (@Relation) */
)
)
val castList: List<CastDbModel>
)
@Entity(
tableName = "movie_cast",
primaryKeys = ["movieIdMap","castIdMap"],
foreignKeys = [
/* A MovieId MUST be a value of an existing id column in the movie table */
ForeignKey(
entity = MovieDbModel::class,
parentColumns = ["id"],
childColumns = ["movieIdMap"],
/* Optional (helps maintain referential integrity) */
/* if parent is deleted then children rows of that parent are deleted */
onDelete = ForeignKey.CASCADE,
/* if parent column is changed then the column that references the parent is changed to the same value */
onUpdate = ForeignKey.CASCADE
),
ForeignKey(
entity = CastDbModel::class,
parentColumns = ["id"],
childColumns = ["castIdMap"],
onDelete = ForeignKey.CASCADE,
onUpdate = ForeignKey.CASCADE
)
]
)
data class MovieCastCrossRef(
val movieIdMap: Int,
@ColumnInfo(index = true)
val castIdMap: Int
)
1条答案
按热度按时间6yjfywim1#
每个cast必须有唯一的id,否则会发生冲突。在您的例子中,如果使用相同的id,则由于使用
OnConflictStrategy.REPLACE
,冲突会导致根据新的强制转换用数据替换强制转换。要插入新的强制转换,应该插入允许生成id的新强制转换(在AutoGenerate=False的情况下,通过将id指定为空),检索生成的id,例如使用
fun insertCast (cast: List <CastDbModel>): LongArray
但是,对于
val id: Int,
,您不能指定NULL。因此,您应该使用var id:int?=NULL(与Movie相同)。然后,当您想要向Movie中添加一个演员时,您可以插入一个MovieCastCrossReference,其MovieIdMap作为来自相应Movie的id,CastIdMap作为来自各个演员的id。
对您的代码进行一些细微的更改:
并使用@DAO注解的接口:-
在活动中使用@数据库注解类(为方便和简洁起见,使用.AllowMainThredQueries)命名数据库和以下代码:-
日志包括:-
为了演示奖金,插入与单个电影相关的整个演员列表。MOVICE_CAST表最终为:-