我有这段代码来创建实现单个接口的多个对象。由于这些对象实现的是单个接口,因此我将这些对象存储在另一个数据类中,作为具有基本接口类类型的列表。
当我将这些对象存储在会议室数据库中时,我为不同类型的对象创建了多个实体,并根据它们在相应表中的类型进行保存。 实体看起来像这样
@Entity(tableName = "blocks",
foreignKeys = [
ForeignKey(entity = MessageEntity::class, parentColumns = ["id"],
childColumns = ["message_id"], onDelete = ForeignKey.CASCADE)])
data class BlockEntity(
@PrimaryKey
var _id: String,
@ColumnInfo(name = "message_id")
val messageId: String,
@ColumnInfo(name = "block_type")
val type: String? = null,
@ColumnInfo(name = "block_id")
val blockId: String? = null,
@ColumnInfo(name= "has_accessory")
val hasAccessory: Boolean = false,
@ColumnInfo(name= "has_elements")
val hasElements: Boolean = false,
@Embedded val text: TextObject? = null
): BaseMessageEntity
块实体在映射回对象时包含丰富的消息对象。这些实体在BlockEntity中的外键为_id
富消息对象实体看起来像:
按钮元素
data class BlockButtonElementEntity(
val blockId: String,
val type: String,
val actionId: String,
@ColumnInfo(name = "block_type")
val blockType: String? = null,
@Embedded(prefix = "button_") val text: TextObject,
val url: String? = null,
val value: String? = null,
val style: String? = null,
val confirm: String? = null
): BaseMessageEntity {
@PrimaryKey(autoGenerate = true)
var id: Long? = null
}
溢出元素
data class BlockOverflowElementEntity(
val blockId: String,
val type: String,
val actionId: String,
@ColumnInfo(name = "block_type")
val blockType: String? = null,
@Embedded(prefix = "button_") val text: TextObject,
val overflowText: String? = null
val overflowDescription: String? = null
): BaseMessageEntity {
@PrimaryKey(autoGenerate = true)
var id: Long? = null
}
现在,我想根据它们的_id的blockelemententity来检索这些丰富的消息对象,并且由于块可包含多种类型的丰富消息对象,因此如何从多个表中检索数据。
例如:
元素-> [按钮,溢出]
或
元素-> [按钮,按钮]
按钮,溢出实现相同的界面。
示例:
@JsonSerializable
data class ActionBlock(
override val type: String,
@Json(name = "block_id") override val blockId: String? = null,
var elements : List<Element>
) : Block
在保存的同时,我可以根据元素的类型将元素保存到不同的表中,但是如何检索它们并映射到List。