我想在Hibernate中创建一个manyToMany-Relation,只有“persist”作为级联类型。
我的餐点看起来像这样:
public class Meal {
@ManyToMany(cascade = {CascadeType.PERSIST})
@JoinTable(name="meal_ingredient_relation",
joinColumns={@JoinColumn(name="meal_id")},
inverseJoinColumns={@JoinColumn(name="ingredient_id")})
private Set<Ingredient> ingredients = new HashSet<>();
...
}
我的成分类看起来像这样:
public class Ingredient {
@ManyToMany(mappedBy = "ingredients", cascade = {CascadeType.PERSIST})
private Set<Meal> meals = new HashSet<>();
...
}
如果我想用一些食材制作一些食物
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
Ingredient ingredient1 = new Ingredient("in1");
Ingredient ingredient2 = new Ingredient("in2");
Meal meal1 = new Meal("meal1", 100);
Meal meal2 = new Meal("meal2", 200);
meal1.getIngredients().add(ingredient1);
meal1.getIngredients().add(ingredient2);
meal2.getIngredients().add(ingredient1);
session.save(meal1);
session.save(meal2);
我收到以下错误:
org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: hibernate.entities.Ingredient
答案 0 :(得分:1)
您必须为setIngredients
课程中的Meal
添加注释:
@Cascade({CascadeType.SAVE_UPDATE, CascadeType.DELETE})
或者如果您使用的是XML映射:
<set name="ingredients" cascade="save-update, delete" ...
显然只在需要时使用DELETE
。