如何选择与ROOM具有1:1关系的模型?

时间:2018-02-10 08:00:39

标签: android android-room android-architecture-components

让我们假设以下简单架构:

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);

我不喜欢我的解决方案,因为:

  1. 内部会议室在一个交易中执行两个查询,希望能够通过单个查询获得。
  2. The relations must be a List or Set even in 1:1 relations,这令人困惑,需要编写不必要的检查和评论。但是,同一篇文章说它可以通过连接查询来完成,但是没有说明如何!

0 个答案:

没有答案