简体   繁体   中英

org.hibernate.NonUniqueObjectException Example

I read a lot of information about this exception, but it very difficult for me.

Can you write most simple example, which will have this exception?

It will happen when you try to update an entity by using :

session.saveOrUpdate(entity);

this because the entity you trying to update has the same ID or PK with that one in the database, actually its prefered to use merge instead of saveOrUpdate :

session.merge(entity);

Here is a full example for this exception:

        Person person = new Person();
        person.setName("NAME");

        Session session = sessionFactory.openSession();
        Transaction transaction1 = session.beginTransaction();
        session.persist(person);
        transaction1.commit();
        session.close();

        person.setName("NEW NAME");

        session = sessionFactory.openSession();
        Transaction transaction2 = session.beginTransaction();
        try {

            // Here the exception will be thrown.
            session.saveOrUpdate(person);

            transaction2.commit();
        } catch (NonUniqueObjectException ex) {
            ex.printStackTrace();
        }
        session.close();

It is happening because hibernate uses session for its first level cache and if we already have that object in detached state and again we try to get that in another session with corresponding id and want to update the same object we will get this exception.

Better to use merge() method instead of update.

    Session session = sessionFactory.openSession();
    Transaction transaction1 = session.beginTransaction();
    Person person = new Person();
    person.setName("NAME");
    person.setId(1);//primary key column.
    session.save(person);//making person object persistent.
    transaction1.commit();
    person.setName("some another name");//modifying detached object 

    Session session2 = sessionFactory.openSession();
    Transaction transaction2 = session2.beginTransaction();
    Person updatedPerson=(Person)session2.get(Person.class,1);//now same object with persistent state attached to session2.
     //session.update(person);//will throw exception because update will try to reattach person object to session2 and already one persistent object with same identifier  updatedPerson object existed in session2 so it will throw this exception.

     session2.merge(person);//it will execute fine.
     transation2.commit();
     session2.close();

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