java - Spring Boot:无法发布到多对多关系
问题描述
我有两个实体Meal
,Mealplan
它们处于@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 添加照常工作。
解决方案
根据您的代码,由于您在实体 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 插入时适用。
推荐阅读
- sql - SQL 查询未返回预期结果
- javascript - 纯 JavaScript 防止键盘输入/单击,直到计时器用完
- .htaccess - How can I Redirect subdomain with path to root domain without this path
- sql - SQL MAX() 函数未按预期工作
- excel - 如何在没有VBA的情况下在EXCEL中反转文本
- tensorflow2.0 - 使用损失`binary_crossentropy`时。这种损失期望目标具有与输出相同的形状
- sql - Bigquery Full Join ON 多个条件
- php - 我无法使用此代码记录我的应用程序的第一个用户的原因可能是什么
- android - 55" 巨型显示器的 android 资产大小和 dpi
- javascript - 删除 Google App Script 中数组中的特定空项