[英]How to write a one to (many pojos of two embedded entities) in Android Room
How do I write a one to many relationship where the many is a pojo of two other embedded entities?如何编写一对多关系,其中 many 是其他两个嵌入式实体的 pojo? There may be multiple Bs for one A but only one B for one A per DataList.每个DataList 可能有多个B 对应一个A,但只有一个B 对应一个A。
Here is a simplification of my code.这是我的代码的简化。
@Entity(tableName = "as")
public class A{
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "a_id")
private int mId;
@ColumnInfo(name = "a_type")
private String mType;
//getters and setters
}
@Entity(tableName = "bs")
public class B{
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "b_id")
private int mId;
@ColumnInfo(name = "b_type")
private String mType;
@ColumnInfo(name = "list_id")
private int mListId;
//getters and setters
}
@Entity(tableName = "data_lists")
public class DataList{
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "data_list_id")
private int mId;
//getters and setters
}
public class AandB {
@Embedded
private A mA;
@Embedded
private B mB;
//getters and setters
}
public class DataListWithAandBs{
@Embedded
private DataList mDataList;
@Relation(
parentColumn = "data_list_id",
entityColumn = "list_id")
private List<AandB> mAandBList;
//getters and setters
}
@Dao
public interface DataListWithAandBsDao {
@Query("SELECT * FROM data_lists LEFT JOIN (SELECT * FROM as LEFT JOIN bs ON a_type = b_type) ON list_id = data_list_id")
LiveData<List<DataListWithAandBs>> getDataListsWithAsandBs();
}
When I compile I receive the error: The class must be either @Entity or @DatabaseView.编译时收到错误:类必须是@Entity 或@DatabaseView。 I don't want the list to be an entity though I want it to be a list of Pojos.我不希望该列表是一个实体,尽管我希望它是一个 Pojo 列表。 Is this possible to do with room?这可能与房间有关吗?
I believe you need to set the entity on the relation as follows:我相信您需要按如下方式在关系上设置实体:
public class DataListWithAandBs{
@Embedded
private DataList mDataList;
@Relation(
parentColumn = "data_list_id",
entityColumn = "list_id",
entity = A.java
)
private List<AandB> mAandBList;
//getters and setters
}
Because you want to fetch a relation from another table but want the return type to be something other than the table's entity.因为您想从另一个表中获取一个关系,但希望返回类型不是该表的实体。
I did something similar in this project: https://github.com/emmaguy/room-playground/blob/master/app/src/main/java/com/monzo/room_playground/Database.kt#L33我在这个项目中做了类似的事情: https : //github.com/emmaguy/room-playground/blob/master/app/src/main/java/com/monzo/room_playground/Database.kt#L33
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.