房间复合主键链接到外键

2024-03-26

我正在使用 Room 数据库实现一个 Android 应用程序,并且对这个数据库中的关系有一个小问题。

我有两张桌子:

@Entity(tableName = "foods", primaryKeys = {"id", "language_id"},
        indices = {@Index(value = {"id", "language_id"}, unique = true)},
        inheritSuperIndices = true)
public class Food {

    @NonNull
    @ColumnInfo(name = "id")
    private String mId;

    @NonNull
    @ColumnInfo(name = "language_id")
    private String mLanguageId;

}

@Entity(tableName = "ingredients", primaryKeys = {"id", "language_id"},
        indices = {@Index(value = {"id", "language_id"}, unique = true), 
        @Index(value = {"food_id", "food_language_id"}, unique = true)},
        foreignKeys = {@ForeignKey(entity = Food.class, parentColumns ="id", 
        childColumns = "food_id", onUpdate = CASCADE, onDelete = CASCADE),
        @ForeignKey(entity = Food.class, parentColumns = "language_id", 
        childColumns = "food_language_id", onUpdate = CASCADE, onDelete = 
        CASCADE)},
        inheritSuperIndices = true)
public class Ingredient {

    @NonNull
    @ColumnInfo(name = "id")
    private String mId;

    @NonNull
    @ColumnInfo(name = "language_id")
    private String mLanguageId;

    @ColumnInfo(name = "food_id")
    private String mFoodId;

    @ColumnInfo(name = "food_language_id")
    private String mFoodLanguageId;

}

表“Food”和“Ingredient”都有复合主键(“id”、“language_id”)。 Food 对象必须包含一个 List,当然还有一个 @Relationship

public class FoodWithIngredients extends Food{

    @Relation(parentColumn = "id", entityColumn = "food_id", entity = 
    Ingredient.class)
    private List<Ingredient> mIngredients;

}

在我尝试运行此代码后收到这些消息

警告:

food_language_id 列引用了外键,但它不是 一个索引。每当父表存在时,这可能会触发全表扫描 已修改,因此强烈建议您创建一个涵盖此的索引 柱子。

Error:

Ingredient has a foreign key (food_id) that references Food (id) but Food does not have a unique index on those columns nor the columns are its primary key. SQLite requires having a unique constraint on referenced parent columns so you must add a unique index to Food that has (id) column(s).

有人可以帮我吗?

提前致谢 :)


好吧,我发现我的错误在哪里了。我的@ForeignKey错了,正确的是:

@ForeignKey(
             entity = Food.class,
             parentColumns = {"id", "language_id"},
             childColumns = {"food_id", "food_language_id"},
             onUpdate = CASCADE, onDelete = CASCADE)

不同之处在于,我在“parentColumns”和“childColumns”中放置了多个列,并且它工作正常。

@Danail Alexiev 插入是这样的:

@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertFoods(List<Food> foods);

@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertIngredients(List<Ingredient> ingredients);

@Transaction
public void insertFoodData(List<Food> foods, RulesOfGolfDatabase database) {
    if (foods != null && database != null) {
        insertFoods(foods);
        for (Food food : foods) {
            insertIngredients(food.getIngrediants());
        }
    }
}

这里最重要的是,您必须首先插入 @Relation 的所有者(在本例中是 Food),然后插入关系中的每个数据

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

房间复合主键链接到外键 的相关文章

随机推荐