我目前有两个类Recipes和Ingredients,用户在其中输入配方和与该配方相关的配料。我正在确保每一种配料都是数据库中唯一的,因此需要与我的食谱和配料建立多对多的关系。
然而,我的问题是,我只能显示配方类中的值,当我打印配料时,它是空的。。。
配方类别:
`@Entity(tableName = "recipe_table")
public class Recipe {
@PrimaryKey(autoGenerate = true)
public Integer recipeId;
@NonNull
public String title;
@NonNull
public String instructions;
public Integer rating;
public Recipe( @NonNull String title, @NonNull String instructions, Integer rating) {
this.title = title;
this.instructions = instructions;
this.rating = rating;
}
public Integer getId(){
return recipeId;
}
public String getTitle() {
return title;
}
public String getInstructions() {
return instructions;
}
public Integer getRating() {
return rating;
}
}`
成分类别:
@Entity(tableName = "ingredients_table")
public class Ingredients {
@PrimaryKey(autoGenerate = true)
@NonNull
public Integer ingredientId;
@NonNull
public String ingredients;
public Ingredients(@NonNull String ingredients) {
this.ingredients = ingredients;
}
public String getIngredients(){
return ingredients;
}
}
交叉引用和从食谱中获取成分的类:
RecipeIngredientsRef类:
@Entity(tableName = "recipe_ingredients_table", primaryKeys = {"recipeId", "ingredientId"})
public class RecipeIngredientsRef {
@ColumnInfo @NonNull
public Integer ingredientId;
@ColumnInfo @NonNull
public Integer recipeId;
}
RecipeIngredients加入课程:
public class RecipeIngredientsJoin{
@Embedded public Recipe recipe;
@Relation(
parentColumn = "recipeId",
entityColumn = "ingredientId",
associateBy = @Junction(RecipeIngredientsRef.class)
)
public List<Ingredients> ingredients;
public List<Ingredients> getIngredients() {
return ingredients;
}
}
还有我的DAO:
bothDAO:
@Dao
public interface bothDAO {
@Transaction
@Query("SELECT *, * FROM recipe_table INNER JOIN ingredients_table ON recipeId = ingredientId")
public LiveData<List<RecipeIngredientsJoin>> getAllIngredientsFromRecipe();
我使用这个DAO是为了显示我的项目,如果你需要查看我的数据库类来帮助解决这个问题,请告诉我!
您似乎滥用了多对多关系。这个查询就足够了:
@Transaction
@Query("SELECT * FROM recipe_table") // <--- no need to JOIN, Room do it for you
// In addition, condition `INNER JOIN ingredients_table ON recipeId = ingredientId` is wrong,
// since you're trying to match ingredients & recipes ids
public LiveData<List<RecipeIngredientsJoin>> getAllIngredientsFromRecipe();
此方法应该返回您想要的内容。当然,对于RecipeIngredientsRef
表,应该同时包含配方和配料的外键。