【发布时间】:2020-02-24 01:04:33
【问题描述】:
我有两个实体 Meal 和 Mealplan 在 @ManyToMany 关系中。每个 Mealplan 可以有不同的 Meal,每个 Meal 可以在多个 Mealplan 中。
@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 添加照常工作。
【问题讨论】:
-
您要做什么:编辑现有记录或添加新实体?您是否启用了 SQL 日志记录。生成的 SQL 是什么?
标签: java spring spring-boot spring-data-jpa spring-data