Question

I have a problem to save more than one objects to database. I get org.hibernate.NonUniqueObjectException: A different object with the same identifier value was already associated with the session My code: Configuration cfg = new Configuration(); cfg.configure("hibernate.cfg.xml");

    ServiceRegistry registry = new StandardServiceRegistryBuilder().applySettings(
            cfg.getProperties()).build();
    SessionFactory factory = cfg.buildSessionFactory(registry);
    Session session = factory.openSession();
    Transaction t = session.beginTransaction();

    Person p1 = new Person();
    p1.setFirstName("Name1");
    p1.setLastName("Surname1");

    session.persist(p1);

    Person p2 = new Person();
    p2.setFirstName("Name2");
    p2.setLastName("Surname2");

    session.persist(p2);
    t.commit();
    session.close();

All works fine, when I persist only one object. Please help.

Edited:

Problem was in mapping file (*.hbm.xml): This code means, that i must define IDs in java code

<id name="id" type="int">
    <column name="ID" />
    <generator class="assigned" />
</id>

This code sets IDs automaticaly:

<id name="id" type="int">
    <column name="ID" />
    <generator class="increment" />
</id>

Now each new object automaticly has unique ID

Was it helpful?

Solution

The problem seems to be in the Person class, in the key generation strategy. Which one are you using? The error means that when attaching the second person to the session, the first person is already there with the same database Id.

Try to ensure that no values are being set in @Id field, let Hibernate generate a value for it using a key generation strategy. Here is a starting point:

@Id
@GeneratedValue(strategy= GenerationType.AUTO)
protected Long id;

Also make sure that in the constructor of Person no default value for the key is being used.

OTHER TIPS

IIRC, this can happen if your equals() method doesn't differentiate these objects.

Can you try saveOrUpdate() instead of persist?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top