java Android Room问题使用适配器和循环查看器以多对多关系显示两个表中的数据
我目前有两个类Recipes and Components,用户在其中输入一个配方和与该配方配套的配料。我要确保数据库中的每种配料都是唯一的,因此需要与我的食谱和配料建立多对多关系
然而,我的问题是,我只能显示配方类中的值,当我打印配料时,它是空的
食谱类:
`@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;
}
}
交叉参考并从食谱中获取配料的课程:
ReceiveCreditsRef类别:
@Entity(tableName = "recipe_ingredients_table", primaryKeys = {"recipeId", "ingredientId"})
public class RecipeIngredientsRef {
@ColumnInfo @NonNull
public Integer ingredientId;
@ColumnInfo @NonNull
public Integer recipeId;
}
RecipeIngredientsJoin类:
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
public interface bothDAO {
@Transaction
@Query("SELECT *, * FROM recipe_table INNER JOIN ingredients_table ON recipeId = ingredientId")
public LiveData<List<RecipeIngredientsJoin>> getAllIngredientsFromRecipe();
我使用这个DAO是为了显示我的项目,如果你需要查看我的数据库类来帮助解决这个问题,请告诉我
# 1 楼答案
你似乎误用了多对多的关系。 这个问题就足够了:
此方法应该返回您想要的内容。当然,对于这个
RecipeIngredientsRef
表应该包含食谱和配料的外键