Android Room库 - 选择嵌入实体的所有字段

时间:2018-01-03 13:33:25

标签: android entity-relationship android-room

我有两个具有外键关系的实体:productcategory

@Entity(primaryKeys = "id")
public class Product {
    public final long id;

    @NonNull
    public final String name;

    @ForeignKey(entity = Category.class, parentColumns = "id", childColumns = "categoryId")
    public final long categoryId;

    public Product(long id, @NonNull String name, long categoryId) {
        this.id = id;
        this.name = name;
        this.categoryId = categoryId;
    }
}

@Entity(primaryKeys = "id")
public class Category {
    public final long id;

    @NonNull
    public final String name;

    public Category(long id, @NonNull String name) {
        this.id = id;
        this.name = name;        
    }
}

我想为两个实体选择所有字段。我已为其定义了一个单独的实体,其中包含@Embedded注释:

public class ProductWithCategory {
    @NonNull
    @Embedded(prefix = "product_")
    public final Product product;

    @NonNull
    @Embedded(prefix = "category_")
    public final Category category;

    public ProductWithCategory(@NonNull Product product, @NonNull Category category) {
        this.product = product;
        this.category = category;
    }
}

现在我可以创建一个这样的查询:

@Query("SELECT product.id as product_id, product.name as product_name, product.categoryId as product_categoryId, category.id as category_id, category.name as category_name FROM product JOIN category on categoryId = category.id WHERE product.id = :id")
LiveData<ProductWithCategory> getProduct(long id);

问题是如果我有5-10个字段的实体,我必须手动指定所有变得过于冗长的字段。是否可以使用一些通配符方法而无需手动指定所有字段?

1 个答案:

答案 0 :(得分:4)

最后我使用@Relation注释来解决这个问题。唯一的缺点是我必须使用ListSet,即使在这种情况下它是0或1实体:

public class ProductWithCategory {
    @NonNull
    @Embedded
    public final Product product;

    @Relation(parentColumn = "categoryId", entityColumn = "id", entity = Category.class)
    public List<Category> category;

    public ProductWithCategory(@NonNull Product product) {
        this.product = product;
    }
}

但这简化了查询:

@Query("SELECT * FROM product WHERE product.id = :id")
LiveData<ProductWithCategory> getProduct(long id);