我从服务器接收到对象MyResponse,其中包含两个列表:
data class MyResponse(
var field: List<Field>?,
var group: List<Group>?
)
然后使用ROOM将其保存到两个不同的表中
@Dao
interface MyDao {
@Insert
fun saveField(field: List<SavedField>)
@Insert
fun saveGroup(group: List<SavedGroup>)
}
SavedField
@Entity
data class SavedField (
@ColumnInfo(name = "field")
var field: String
) {
@PrimaryKey(autoGenerate = true)
var id: Int = 0
}
SavedGroup
@Entity
data class SavedGroup(
@ColumnInfo(name = "group")
var group: String
) {
@PrimaryKey(autoGenerate = true)
var id: Int = 0
}
但是将数据写入数据库后如何再次获得MyResponse
对象?当然,我可以为每个表使用两个@Query,但是我认为这不是最好的解决方案。
答案 0 :(得分:1)
检查以下代码可能会对您有所帮助。
解决方案1
@Query("SELECT * FROM Field")
List<FieldAndGroup> findFieldAndGroup();
public class FieldAndGroup {
@Embedded
Field field;
@Relation(parentColumn = "Field.feild_id", entityColumn = "Group.id")
//Relation returns a list
//Even if we only want a single Bar object ..
List<Group> group;
//Getter and setter...
}
解决方案2
@Query("SELECT Group.*, Field.* FROM Group INNER JOIN Field ON Field.grpId = Group.id")
List<GroupAndField> findAllGroupAndField();
public class GroupAndField {
@Embedded
Group group;
@Embedded
Field field;
//Getter and setter...
}