• Register
search
Log In
0 votes
120 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?

7.5k points

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.

36.1k 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();

 

12.8k points

Related questions

0 votes
2 answers 46 views
46 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
2 answers 74 views
74 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
1 vote
1 answer 199 views
199 views
Problem : When I try to compile my spring project, I always face the below error : Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Invocation of init method failed I have the ... >1.4.1.RELEASE</version> <relativePath /> <!-- lookup parent from repository --> </parent> . . .
asked Dec 12, 2019 alecxe 7.5k points
0 votes
1 answer 592 views
592 views
Problem : I am using the Hibernate for a first time for my project and I am very new to Hibernate. I think I have followed all the instructions written in some tutorials but still I keep getting the below Exception that is in my title: Exception in thread "main" ... should just change a connection.pool_size property, but if I do so it guesses that I only will get more errors. Can anyone help me?
asked Jan 30 jwilliam 3.9k points
0 votes
1 answer 19 views
19 views
Problem : I am beginner to html. I have recently started learning html. When I tried to process my web page in a W3C validator it started showing me below error &ldquo;Start tag head seen but an element of the same type was already open&rdquo;. But when I try to remove the ... I re add a start tag then the error comes back again. How can I fix this issue? Can anybody help me in fixing this issue?
asked Mar 6 mphil 2.3k points