Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package com.example.stuff;
import java.util.List;
import androidx.room.Dao;
import androidx.room.Embedded;
import androidx.room.Entity;
import androidx.room.Insert;
import androidx.room.PrimaryKey;
import androidx.room.Query;
import androidx.room.Relation;
import androidx.room.Transaction;
@Entity
class Recipe {
@PrimaryKey
private int id;
private String name;
int getId() {
return id;
}
}
@Entity
class Ingredient {
@PrimaryKey(autoGenerate = true)
private int id;
private int recipeId;
void setRecipeId(int recipeId) {
this.recipeId = recipeId;
}
}
class RecipeWithIngredients {
@Embedded
Recipe recipe;
@Relation(parentColumn = "id", entityColumn = "recipeId", entity = Ingredient.class)
private List<Ingredient> ingredients;
List<Ingredient> getIngredients() {
return ingredients;
}
}
//////
@Dao
abstract class RecipeDao {
@Insert
abstract void insertRecipe(Recipe recipe);
@Insert
abstract void insertIngredients(List<Ingredient> ingredients);
@Transaction
void saveRecipeWithIngredients(RecipeWithIngredients recipeWithIngredients) {
// loop thru ingredients to make sure the recipe id is set before we insert
List<Ingredient> ingredients = recipeWithIngredients.getIngredients();
for (Ingredient ingredient : ingredients) {
ingredient.setRecipeId(recipeWithIngredients.recipe.getId());
}
insertIngredients(ingredients);
insertRecipe(recipeWithIngredients.recipe);
}
@Transaction
@Query("SELECT * FROM recipe")
abstract List<RecipeWithIngredients> getRecipesWithIngredientsLiveData();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment