I\'ve added one to many relationship in Room using Relation. I referred to this post to write the following code for relation in Room.
The post tells how to read th
I managed to insert it properly with a relatively simple workaround. Here are my entities:
@Entity
public class Recipe {
@PrimaryKey(autoGenerate = true)
public long id;
public String name;
public String description;
public String imageUrl;
public int addedOn;
}
@Entity
public class Ingredient {
@PrimaryKey(autoGenerate = true)
public long id;
public long recipeId;
public String name;
public String quantity;
}
public class RecipeWithIngredients {
@Embedded
public Recipe recipe;
@Relation(parentColumn = "id",entityColumn = "recipeId",entity = Ingredient.class)
public List ingredients;
I am using autoGenerate for auto-increment value(long is used with a purpoes). Here is my solution:
@Dao
public abstract class RecipeDao {
public void insert(RecipeWithIngredients recipeWithIngredients){
long id=insertRecipe(recipeWithIngredients.getRecipe());
recipeWithIngredients.getIngredients().forEach(i->i.setRecipeId(id));
insertAll(recipeWithIngredients.getIngredients());
}
public void delete(RecipeWithIngredients recipeWithIngredients){
delete(recipeWithIngredients.getRecipe(),recipeWithIngredients.getIngredients());
}
@Insert
abstract void insertAll(List ingredients);
@Insert
abstract long insertRecipe(Recipe recipe); //return type is the key here.
@Transaction
@Delete
abstract void delete(Recipe recipe,List ingredients);
@Transaction
@Query("SELECT * FROM Recipe")
public abstract List loadAll();
}
I had problem linking the entities, auto generate produced "recipeId=0" all the time. Inserting the recipe entity firstly fixed it for me.