我正在使用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'和'成分'拥有复合主键(' id',' language_id')。 Food对象必须包含List,当然还有@Relationship
public class FoodWithIngredients extends Food{
@Relation(parentColumn = "id", entityColumn = "food_id", entity =
Ingredient.class)
private List<Ingredient> mIngredients;
}
我尝试运行此代码后收到这些消息
WARNNING:
food_language_id列引用了一个外键,但它不属于 一个索引。无论父表是什么,这都可能触发全表扫描 已修改,因此强烈建议您创建一个涵盖此内容的索引 列。
错误:
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).
有人可以帮我吗?
提前致谢:)
答案 0 :(得分:2)
好的,我发现我的错误在哪里。我的@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),然后插入关系中的每个数据