让我们假设以下简单架构:
Item | item_id, category_id, name
Category | category_id, name
有了房间,可以用以下实体来描述。
@Entity(tableName = "item", foreignKeys = {/* fk to category */})
public class Item {
@PrimaryKey
@ColumnInfo(name = "item_id")
public final int itemId;
@ColumnInfo(name = "category_id", index = true)
public final int categoryId;
@ColumnInfo(name = "name")
public final int name;
// constructor setting the properties is omitted
}
@Entity(tableName = "category")
public class Category {
@PrimaryKey
@ColumnInfo(name = "category_id")
public final int categoryId;
@ColumnInfo(name = "name")
public final String name;
// constructor setting the properties is omitted
}
如何获得既包含Item
又包含Category
的POJO,最好只使用一个查询?
这是我设法得到的最接近的:
public class ItemWithCategory {
public Item item;
@Relation(parentColumn = "category_id", entityColumn = "category_id")
public List<Category> category;
}
// this is in my @Dao
@Transaction
@Query("SELECT * FROM item WHERE item_id = :itemId")
abstract Flowable<ItemWithCategory> getItemWithCategory(int itemId);
我不喜欢我的解决方案,因为:
List
or Set
even in 1:1 relations,这令人困惑,需要编写不必要的检查和评论。但是,同一篇文章说它可以通过连接查询来完成,但是没有说明如何!