@一对多关系在春季不起作用

时间:2020-06-29 22:55:19

标签: spring spring-boot jpa spring-data-jpa one-to-many

我有一个实体食谱,其与配料的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存储库。

我没有任何错误,但是当我尝试检索一个对象时,即使它们已保存在表中,也没有任何成分(但是主成分为cheme_id = null)。 我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

将您的ingredients初始化为

@OneToMany(cascade = CascadeType.ALL, mappedBy = "recipe")
private Set<Ingredient> ingredients = new HashSet<>(); 

将您的控制器更改为

@GetMapping("/insert")
    public Recipe addRecipe() {
        Ingredient ingredient = new Ingredient("ingredient-"+Math.random(), 10));
        Recipe newRecipe = new Recipe("Recipe-"+Math.random(),
                null, null); //constructor without ingredient arg
        newRecipe.getIngredients.add(ingredient);
        ingredient.setRecipe(newRecipe);
        return recipeRepository.save(newRecipe);
    }