I'm trying to make a recipe app and I have these models:
Recipe
public class Recipe {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String title;
private Integer prepTime;
private Integer cookTime;
@OneToMany(fetch = FetchType.LAZY)
private ArrayList<Ingredient> ingredients;
private String instructions;
private String notes;
public Recipe(String title, Integer prepTime, Integer cookTime, ArrayList<Ingredient> ingredients, String instructions, String notes) {
this.title = title;
this.prepTime = prepTime;
this.cookTime = cookTime;
this.ingredients = ingredients;
this.instructions = instructions;
this.notes = notes;
}
Ingredient
public class Ingredient {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "product_id")
private Product product;
private Integer quantity;
private Integer price;
public Ingredient(Product product, int quantity, Integer price) {
if (product != null) {
this.product = product;
}
this.quantity = quantity;
this.price = Objects.requireNonNullElseGet(price, () -> this.quantity * this.product.getPricePerUnit());
}
Product
public class Product {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;
private String unit;
private Integer pricePerUnit;
public Product(String name, String unit, Integer price) {
this.name = name;
this.unit = unit;
this.pricePerUnit = price;
}
I'm trying to create a new recipe and ingredients using existing products in my database, so I need to:
- Get product ids from the JSON
- Look up the product ids in the ProductRepository and return the relevant Product
- Use those products in the Ingredients constructor to create a list of ingredients
- Pass that list of ingredients to the Recipe constructor
My problem is how to reflect all this in my Recipe controller:
@PostMapping("/add")
public void addRecipe(@RequestBody ??? data)
This is my Json data for testing:
{
"title": "Test Recipe",
"prepTime": 20,
"cookTime": 50,
"ingredients": [
{
"product": 1,
"quantity": 30
}
],
"instructions": "blah blah",
"notes": "etc"
}
Ideally I'd like to pass multiple parameters to @RequestBody (the list of product ids, the values for the remaining Ingredient fields, and the values for the remaining Recipe fields). Then I could proceed from step 2 above. The problem is that @RequestBody can't accept more than 1 parameter. Is there any way to make my controller find the product IDs first and create the Ingredients before trying to create a Recipe?
I have seen a potentially linked question here but it doesn't deal with where/how I can look up the Product id and get the Product before creating the Ingredient.