2017-04-22 30 views
0

我有@Entity的Recipe.java對象:休眠保存到數據庫 「爲重點重複條目 '1' 'UK_2n5xttsxwbyc6x67l0x8phfwn'」

... 
@OneToMany(cascade = CascadeType.ALL) 
private List<Category> category; 
... 

然後Category.java對象爲@Entity:

... 
@OneToOne(cascade = CascadeType.ALL) 
private Name name; 
... 

假設數據庫看起來像這樣(recipe_category表):

enter image description here

然後執行以下代碼(我只是想一個類別添加到配方):

... 
     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' 

那麼,什麼將是解決辦法對於這個問題?

UPDATE:
配方表的結構是這樣的:

enter image description here

類別表結構如下:

enter image description here

所以,問題似乎發生,因爲當recipe.setCategory(categories);被觸發,它會嘗試將ctg保存到數據庫,但它已經存在。我想要的不是將它保存到數據庫(因爲它已經在'category'表中),而是在recipe_category表中添加一個新行。

也許它必須做一些級聯?

+0

我認爲這是由於@OneToMany的誤用,這個答案可能會有所幫助:http://stackoverflow.com/a/ 15802642/7624937 – LLL

+0

你如何創建你的表?你可以發表表格結構,創建腳本或至少定義異常中提到的關鍵字嗎? – infiniteRefactor

+0

@infiniteRefactor我已經更新了關於表結構的一些細節。所以問題不在於'創建'過程,而是當我想將現有類別添加到配方中時。 – Cristian

回答

1

您的關係不是一對多。你希望每個配方有多個類別。我想你也希望每個類別都與多個食譜相關聯。這是一個多對多的關係。您需要使用@ManyToMany註釋來配置您的實體。

另請注意,Hibernate關係始終是單向的。當您將@ManyToMany註釋放入Recipe類中時,您可以訪問與給定配方關聯的類別。爲了獲得反向關係,要獲得給定類別的食譜,您還需要將@ManyToMany註釋的相應屬性添加到Category類。

我想你使用hbm2ddl或類似的方法來自動創建你的表,並且因爲創建表爲一對多關係,你會得到一個錯誤。更具體地說,在單向一對多關係中,連接表中的反向外鍵列(您的recipe_category表中的category_id)具有在其上定義的唯一約束。因此,使用該表格模式,您無法將類別與多個配方關聯。

像這樣的東西應該工作:

// Recipe 
@ManyToMany(cascade=CascadeType.ALL) 
@JoinTable(name="category_map",) 
private List<Category> categories = new ArrayList<>(); 

// Category 
@ManyToMany(cascade=CascadeType.ALL, mappedBy="categories")  
private Set<Recipe> recipes;  
+0

感謝您的解答和解釋。有用。 – Cristian