Possible Duplicate:
Hibernate: different object with the same identifier value was already associated with the session
I get the following error:
a different object with the same identifier value was already associated with the session
I have two types of objects, Course and RecommendedSchedule which has a set of courses. Here are their xml definitions:
<hibernate-mapping>
<class name="database.datatypes.Course" table="courses" lazy="false">
<id name="id" column="ID">
<generator class="assigned"/>
</id>
<property name="name" type="string"/>
<property name="date"/>
</class>
and
<hibernate-mapping>
<class name="database.datatypes.RecommendedSchedule" table="recommended_schedules" lazy="false">
<id name="id" column="ID">
<generator class="increment"/>
</id>
<set name="courses" table="schedules_courses" cascade="save-update" lazy="false">
<key column="course_id"/>
<many-to-many class="database.datatypes.Course"/>
</set>
<property name="semester" type="string"/>
<property name="path" type="string"/>
</class>
Basically if i insert two recommended systems with different sets, but using the same Course objects, it works, but if i do the exact same thing but use different Course objects (with the same values) i get the error.
Anyone knows what I'm doing wrong?
Here is an example for a piece of code that fails:
Session s = db.factory.openSession();
Set<Course> set1 = new HashSet<>();
Set<Course> set2 = new HashSet<>();
Course c1 = new Course(104167L, "Algebra A");
Course c2 = new Course(234114L, "Introduction to CS H and M");
Course c3 = new Course(104012L, "Calculus 1 T");
Course c4 = new Course(234145L, "Digital Systems");
Course c12 = new Course(104167L, "Algebra A");
Course c22 = new Course(234114L, "Introduction to CS H and M");
Course c32 = new Course(104012L, "Calculus 1 T");
Course c42 = new Course(234145L, "Digital Systems");
set1.add(c1);
set1.add(c2);
set1.add(c3);
set2.add(c12);
set2.add(c22);
set2.add(c32);
set2.add(c42);
RecommendedSchedule r1 = new RecommendedSchedule(set1, "General 3 years", "1");
RecommendedSchedule r2 = new RecommendedSchedule(set2, "General 4 years", "1");
Collection<RecommendedSchedule> col = new ArrayList<RecommendedSchedule>();
Collection<Course> col2 = new ArrayList<Course>();
col.add(r1);
col.add(r2);
col2.add(c12);
col2.add(c22);
col2.add(c32);
col2.add(c42);
Transaction t = s.beginTransaction();
s.save(r1);
s.save(r2);
t.commit();
s.close();
if i did instead:
set2.add(c1);
set2.add(c2);
set2.add(c3);
set2.add(c4);
It would've worked. (This of course isn't the real issue, but a simple example)
In the end i simply used merge() instead of save(), seems it solves the problem even though i have a set of objects and not just trying to work with a normal object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With