Nooby
Nooby

Reputation: 115

How to do mapping in Hibernate

I use hibernate (without spring), and I have a problem about mapping. I have 2 entities, "User" and "Enquête", with this mapping code :

Enquête :

@ManyToOne(fetch = FetchType.LAZY)
@Cascade(org.hibernate.annotations.CascadeType.ALL);
private User responsable;

In User :

(nothing about Enquête because there is no "mapped by" for the moment)

And when I try to save a new "Enquête" like that :

private static void addEnqueteInBdd(String titre,Date dateCreation,Date dateFermeture,Boolean cloture,int idEnquete,Formulaire formulaire,User responsable,List<Collecte> collectes) {
        Transaction transaction = null;
        Enquete en = null;
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            transaction = session.beginTransaction();           
            en = new Enquete( titre, dateCreation, dateFermeture, cloture, collectes, formulaire,responsable );
            session.save(en);
            transaction.commit();   
        } catch (Exception e) {
            e.printStackTrace();
            if (transaction != null) {
                transaction.rollback();
            }
            e.printStackTrace();
        }
    }

I have this error :

ERROR: HHH000346: Error during managed flush [Row was updated or deleted by another transaction (or unsaved-value mapping was incorrect) : [Model.User#1]]

PS: It's my first action with hibernate in my code, so I don't think it's about another transaction.

Upvotes: 0

Views: 70

Answers (1)

Maciej Kowalski
Maciej Kowalski

Reputation: 26492

Most likely the User you are passing as a param has been retrieved in another transaction and is detached.

Try to merge first that entity and then perform the save:

        try {
            User responsableMerged = session.merge(responsable);
            transaction = session.beginTransaction();           
            en = new Enquete( titre, dateCreation, dateFermeture, 
                 cloture, collectes, formulaire,responsableMerged );
            session.save(en);
            transaction.commit();   
        }

Also do not use Hibernate specific cascading. Use standard JPA ones on the MAnyToOne

Upvotes: 1

Related Questions