MrV*_*lev 7 sqlite android foreign-keys primary-key android-room
我正在使用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;
}
Run Code Online (Sandbox Code Playgroud)
表“食物”和“成分”都具有复合主键(“ id”,“ language_id”)。Food对象必须包含一个列表,当然还必须包含一个@Relationship
public class FoodWithIngredients extends Food{
@Relation(parentColumn = "id", entityColumn = "food_id", entity =
Ingredient.class)
private List<Ingredient> mIngredients;
}
Run Code Online (Sandbox Code Playgroud)
在我尝试运行此代码后,收到了以下消息
警告:
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).
Run Code Online (Sandbox Code Playgroud)
有人可以帮我吗?
提前致谢 :)
好的,我发现我的错误在哪里。我的@ForeignKey 错了,正确的是这个:
@ForeignKey(
entity = Food.class,
parentColumns = {"id", "language_id"},
childColumns = {"food_id", "food_language_id"},
onUpdate = CASCADE, onDelete = CASCADE)
Run Code Online (Sandbox Code Playgroud)
不同之处在于我在“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());
}
}
}
Run Code Online (Sandbox Code Playgroud)
这里最重要的是你必须首先插入@Relation 的所有者(在这个例子中是 Food),然后是关系中的每个数据
| 归档时间: |
|
| 查看次数: |
3481 次 |
| 最近记录: |