简体   繁体   中英

Hibernate manyToMany only persist

I want to create a manyToMany-Relation in Hibernate with only "persist" as cascade type.

My meal class looks like this:

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<>();
    ...
}

And my ingredient class looks like this:

public class Ingredient {
    @ManyToMany(mappedBy = "ingredients", cascade = {CascadeType.PERSIST})
    private Set<Meal> meals = new HashSet<>();
    ...
}

If I want to create some meals with some ingredients

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);

I get the following error:

org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: hibernate.entities.Ingredient

You have to add an annotation to your setIngredients in the Meal class:

@Cascade({CascadeType.SAVE_UPDATE, CascadeType.DELETE})

Or if you are using XML mapping:

<set name="ingredients" cascade="save-update, delete" ...

obviously use DELETE only if needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM