【问题标题】:@One-to-Many relationship does not working in Spring@One-to-Many 关系在 Spring 中不起作用
【发布时间】: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


    【解决方案1】:

    将您的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);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-24
      • 1970-01-01
      • 2019-07-09
      相关资源
      最近更新 更多