【发布时间】:2020-10-20 04:32:46
【问题描述】:
我有一个实体配方,其关系为 OneToMany 与成分。
@Entity
public class Recipe {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
private String name;
@OneToOne(cascade = CascadeType.ALL) // se eliminiamo la Recipe eliminiamo anche notes
private Notes notes;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "recipe")
private Set<Ingredient> ingredients;
@ManyToMany(fetch=FetchType.EAGER, cascade = CascadeType.ALL)
@JoinTable(name = "recipe_category",
joinColumns = @JoinColumn(name = "recipe_id"),
inverseJoinColumns = @JoinColumn(name = "category_id"))
private Set<Category> categories;
...getter and setter...
}
还有一个实体成分:
@Entity
public class Ingredient {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String description;
private int amount;
@ManyToOne
private Recipe recipe;
...getter and setter...
}
为了测试它,我使用了一个控制器来插入和检索所有行:
@GetMapping({"","/"})
public List<Recipe> allRecipe() {
return recipeRepository.findAll();
}
@GetMapping("/insert")
public Recipe addRecipe() {
Set<Ingredient> ingredients = new HashSet<>();
ingredients.add(new Ingredient("ingredient-"+Math.random(), 10));
Recipe newRecipe = new Recipe("Recipe-"+Math.random(),
null, ingredients, null);
return recipeRepository.save(newRecipe);
}
存储库是 JPA 存储库。
我没有任何错误,但是当我尝试检索一个对象时,即使它们保存在桌子上(但 recipe_id = null),我也没有得到任何成分。 我该如何解决这个问题?
【问题讨论】:
标签: spring spring-boot jpa spring-data-jpa one-to-many