[英]Save an object in multiple other objects using hibernate
我目前嘗試制作一個簡單的目錄Web視圖,我使用Spring和Hibernate來保存數據。 我想要一個Product
Template
,在這個模板中應該有多個Ingredients
也是Products
。
這些是我的課程:
Template.java
@Entity
public class Template extends Product implements Serializable {
@OneToMany(fetch=FetchType.LAZY, cascade = {CascadeType.ALL, CascadeType.MERGE, CascadeType.PERSIST})
private List<Ingredient> ingredients = new ArrayList<>();
public Template(String name, Money price, ArrayList<Ingredient> ingredients) {
super(name, price);
this.ingredients.addAll(ingredients)
}
// Getters and setters...
}
Ingredient.java
@Entity
public class Ingredient extends Product implements Serializable {
public Ingredient(String name, Money price) {
super(name, price);
}
}
Product.java
該類來自salespoint框架。 它處理名稱和價格的保存,但它也處理像Hibernate的ID 。
public void initialize()
該方法提供用於測試目的的偽數據。
public void initialize() {
Ingredient cheese = new Ingredient("Cheese", Money.of(1, "EUR");
Ingredient bacon = new Ingredient("Bacon", Money.of(1, "EUR");
Ingredient tomato = new Ingredient("Tomato", Money.of(1, "EUR");
// add these ingredients into ArrayLists (3 Lists)
// list1: tomato, bacon
// list2: bacon, tomato, cheese
// list3: cheese, tomato
Template pizza1 = new Template("Pizza 1", Money.of(1, "EUR"), list1);
Template pizza2 = new Template("Pizza 2", Money.of(1, "EUR"), list2);
Template salad = new Template("Salad", Money.of(1, "EUR"), list3);
// saving these in a catalog
}
運行此代碼時,我總是得到這種錯誤:
Unique index or primary key violation: "UK_TAGDVK3J2NBLU2MQMBL8HBJV9_INDEX_1 ON PUBLIC.PRODUCT_INGREDIENTS(INGREDIENTS_PRODUCT_ID) VALUES ('f6f05610-ca1f-40b6-b0a8-abaccbc0452b', 2)"; SQL statement:
insert into product_ingredients (template_product_id, ingredients_product_id) values (?, ?) [23505-197]
我這樣解釋這個錯誤:Hibernate嘗試創建一個表來鏈接模板與成分,但成分鍵出現不止一次。
當我嘗試每個列表只添加一種成分時(所以只有一個只有奶酪,一個帶培根,......)它的效果非常好。
我不太清楚如何搜索這個主題,我試着用谷歌搜索它,但我還沒有找到任何東西。 我必須做出哪些更改才能使此代碼生效,以便一個成分對象可以出現在多個模板中?
您在Products
和Ingredients
之間定義了@OneToMany
關系,實際上是@ManyToMany
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.