[英]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.