• Register
0 votes
2.2k views

Problem :

I have some objects in the following configuration:

·  A has the many-to-many relationship with B. (B         has inverse="true")

·  B has the many-to-one relationship with C. (I have cascade set to "save-update")

·  C is the kind of type or category table.

Also primary keys are generated by the database on the save.

But with my data sometimes I run into problems such as  A has the set of different B objects and now these B objects refer to the same C object.

When I try to call session.saveOrUpdate(myAObject) I get following hibernate error which says: "a different object with the same identifier value was already associated with the session: C". I can understand that hibernate cannot insert/update/delete the same object twice in the same session, and so looking for some workaround on this? I don’t think this is the uncommon situation.

One thing I want to mention here is that for architectural reasons beyond my control each read or write needs to be done in a separate session.

Does anybody has any solution on my issue?

6 5 3
7,540 points

Please log in or register to answer this question.

2 Answers

0 votes

Solution :

You just need to Run session_object.clear() and after that just save the new object. This will clear the session for you and  will remove the offending duplicate object from your session.

OR

You can just add the annotation @GeneratedValue to the bean you are inserting.

9 7 4
38,600 points
0 votes

Solution:

Reason Behind this error

Its because the B objects are not referring to the same Java C object instance. They are referring to the same row in the database (i.e. the same primary key) but they're different copies of it.

So what is happening is that the Hibernate session, which is managing the entities would be keeping track of which Java object corresponds to the row with the same primary key.

One option would be to make sure that the Entities of objects B that refer to the same row are actually referring to the same object instance of C. Alternatively turn off cascading for that member variable. This way when B is persisted C is not. You will have to save C manually separately though. If C is a type/category table, then it probably makes sense to be that way.

STEP 1: Just set cascade to MERGE, that should do the trick.

STEP 2:

You only need to do one thing. Run session_object.clear() and then save the new object. This will clear the session (as aptly named) and remove the offending duplicate object from your session.

Follw this below cod it may sort out this issue

@Test
public void testSavePerson() {
    try (Session session = sessionFactory.openSession()) {
        Transaction tx = session.beginTransaction();
        Person person1 = new Person();
        Person person2 = new Person();
        person1.setName("222");
        person2.setName("111");
        session.save(person1);
        session.save(person2);
        tx.commit();
    }
}

Person.java

public class Person {
    private int id;
    private String name;

    @Id
    @Column(name = "id")
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @Basic
    @Column(name = "name")
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

 

add this code on your primary key:

@GeneratedValue(strategy = GenerationType.AUTO)

Transfer the task of assigning the object ID from Hibernate to the database by using:

<generator class="native"/>

Another way to solve the above problem will be to override the hashcode().
Also flush the hibernate session before and after save

getHibernateTemplate().flush();

 

10 6 4
31,120 points

Related questions

0 votes
1 answer 3 views
3 views
Problem: Why am I getting this exception? package com.domain.idea; import javax.persistence.CascadeType; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; ... (AnnotationConfiguration.java:867) at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:669) ... 145 more
asked 3 days ago Yeamin 21.4k points
0 votes
2 answers 162 views
162 views
Problem : Here I want to copy all the objects in the List with object1 to a list with object2: Following is my code snip: List<EmployeeAmManegmentModel> AM = employee.amEmployeeDeatails(); List<EmployeeRmManegmentModel> RM = employee.rmEmployeeDeatails(); List< ... Long status; private String employeeType; How can I copy the result from one list of different object type to another?
asked Dec 3, 2019 alecxe 7.5k points
0 votes
1 answer 4 views
4 views
Problem: I get the following exception: Exception in thread "main" org.hibernate.LazyInitializationException: could not initialize
asked Apr 25 ummeshani 8.8k points
0 votes
1 answer 11 views
11 views
Problem: the database returned no natively generated identity value.
asked Feb 22 Dan phillip 4.8k points
0 votes
1 answer 157 views
157 views
Problem: I am working on Hibernate and now I am facing what I believe is a simple problem with the Hibernate but still I can't solve it. I have written a simple class I would like to persist but still keep facing below error: SEVERE: Field 'id' doesn't have a ... that is not working for me. Initializing the id also did not help me either! I am looking for Hibernate expert to fix my above error.
asked Jul 30, 2020 Raphael Pacheco 4.9k points
0 votes
2 answers 194 views
194 views
Problem : I am facing the following error when I save the object using Hibernate: object references an unsaved transient instance - save the transient instance before flushing:
asked Nov 14, 2019 peterlaw 6.9k points
0 votes
1 answer 37 views
37 views
Problem: I need help in solving this error: Could not obtain transaction-synchronized session for current thread.
asked Mar 13 Wafa Abu Yousef 6.1k points
1 vote
1 answer 2.6K views
2.6K views
Problem : I am beginner to spring + hibernate. Recently I have created the application with the use of spring + hibernate but I always face below error. I am trying to work on it for the very first time. Below is the error for your ... ) at coreservlets.StudentDAOImpl.create(StudentDAOImpl.java:19) at coreservlets.MainApp.main(MainApp.java:14) Can somebody help me in overcoming above error?
asked Mar 28, 2020 morrisBson 3.2k points
0 votes
1 answer 4 views
4 views
Problem: This is my StudentDaoImpl class. package com.gavs.dao; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.query.Query; import com.gavs.beans.Result; import com.gavs.beans.Student; import com.gavs. ... xml file in the WEB-INF/classes folder within the WebContent folder. This is A Spring MVC and hibernate project. Thank You
asked Apr 25 Yeamin 21.4k points
0 votes
1 answer 3 views
3 views
Problem: Does anyone know the solution of it? So kindly let me know .. Restful web services with spring and hibernate example
asked Apr 26 Ifra 34.7k points