gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:57:12 25 4
gpt4 key购买 nike

我有两个具有外键关系的实体: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 个字段的实体,这会变得过于冗长。是否可以在不手动指定所有字段的情况下使用一些通配符方法?

最佳答案

最后我使用了@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);

关于Android Room library - 选择嵌入式实体的所有字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48078484/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com