首页 > 解决方案 > Spring Boot:无法发布到多对多关系

问题描述

我有两个实体MealMealplan它们处于@ManyToMany 关系中。每份膳食计划可以有不同的膳食,每份膳食可以在多个膳食计划中。

@Entity
public class Meal {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String name;
    private BigDecimal price;
    private String type;

@ManyToMany(mappedBy = "mealsPerWeek")
private List<Mealplan> mealplan;

@Entity
public class Mealplan {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private int week;

    @ManyToMany
    private List<Meal> mealsPerWeek;

由于我添加了 ManyToMany 关系,因此我无法通过 @Postmapping 将 Meal 添加到 API 中。

膳食控制器

@RestController
@RequestMapping("/meal")
@CrossOrigin(origins = "*", allowedHeaders = "*")
public class MealController {

    @PostMapping
    public void addMeal(@RequestBody Meal meal) {
        mealRepository.save(meal);
    }

MealRepository 类扩展了 JPARepository。

每当我想将某些内容发布到我的实体中时,例如:

{
    "id": 10,
    "name": "Test",
    "price": 3.50,
    "type": "with Meat"
}

出现以下错误: "could not execute statement; SQL [n/a]; constraint [PRIMARY]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement"

通过 INSERT INTO 添加照常工作。

标签: javaspringspring-bootspring-data-jpaspring-data

解决方案


根据您的代码,由于您在实体 Meal 中使用了“mappedBy”,因此这是映射实体,因此 MealPlan 成为所有者实体,即它负责维护关联。

您还需要创建另一个表,让我们调用MealMapping来存储 Meal 和 MealPlan 的映射,字段为 meal_id 和 mealplan_id。

现在您需要在所有者实体中定义 @JoinTable。

@Entity
public class Mealplan {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private int week;

@ManyToMany
@JoinTable(name="MealMapping", joinColumns={@JoinColumn(referencedColumnName="ID")}, 
inverseJoinColumns={@JoinColumn(referencedColumnName="ID")})  
private List<Meal> mealsPerWeek;
}

希望这可以帮助。

此外,它通过 INSERT 查询起作用,因为您已经在 hibernate 中定义了多对多关系,而不是在数据库表上。因此,约束仅在您尝试使用 hibernate 插入时适用。


推荐阅读