【发布时间】:2017-04-22 21:47:26
【问题描述】:
我有带有@Entity 的Recipe.java 对象:
...
@OneToMany(cascade = CascadeType.ALL)
private List<Category> category;
...
然后是带有@Entity 的Category.java 对象:
...
@OneToOne(cascade = CascadeType.ALL)
private Name name;
...
假设数据库看起来像这样(recipe_category 表):
然后执行以下代码(我只是想在配方中添加一个类别):
...
Recipe recipe = recipeRepository.findOne(recipeId);
Category ctg = categoryRepository.findOne(categoryId); // id=1
List<Category> categories = recipe.getCategory();
categories.add(ctg);
recipe.setCategory(categories);
recipeRepository.save(recipe);
...
在recipeRepository.save(recipe) 我收到以下错误:
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '1' for key 'UK_2n5xttsxwbyc6x67l0x8phfwn'
那么解决这个问题的方法是什么?
更新:
配方表结构如下所示:
分类表结构如下:
所以问题似乎发生了,因为当recipe.setCategory(categories); 被触发时,它会尝试将ctg 保存到数据库,但它已经存在。我想要的不是将它保存到 db(因为它已经存在于“类别”表中),而是在 recipe_category 表中添加一个新行。
也许它与级联有关?
【问题讨论】:
-
我认为这是由于滥用@OneToMany,这个答案可能会有所帮助:stackoverflow.com/a/15802642/7624937
-
如何创建表?你能发布表结构、创建脚本或者至少是异常中提到的键的定义吗?
-
@infiniteRefactor 我已经用有关表结构的一些细节更新了这个问题。所以问题不在于“创建”过程,而是当我想将现有类别添加到配方时。
标签: java mysql spring hibernate