arumugam_kasi wrote:
Hi,
Mapping files
===========
<hibernate-mapping package="example">
<class name="House" table="amber_one2many_houses">
<id name="id" column="id"
type="int"
>
<generator class="assigned" />
</id>
<property name="name"/>
<set name="students" lazy="true">
<key column="house"/>
<one-to-many class="Student" />
</set>
</class>
</hibernate-mapping>
<hibernate-mapping package="example">
<class name="Student" table="amber_one2many_students">
<id name="id" column="id"
type="int"
>
<generator class="assigned" />
</id>
<property name="name"/>
<many-to-one name="house" /> <!-- class="House" not-null="true" column="house" unique="true" /> -->
</class>
</hibernate-mapping>
As suggested by previous poster, inverse=true and cascade=all should be set on the <set> tag. But as you saw, that was only part of the problem...
arumugam_kasi wrote:
Code that inserts House
===============
Student st=new Student();
java.util.HashSet students=new java.util.HashSet();
st.setId(10);
st.setName("Arumugam");
Student st1=new Student();
st1.setId(11);
st1.setName("Ramamani");
students.add(st1);
students.add(st);
House house=new House();
house.setName("White House");
house.setId(10);
house.setStudents(students);
hsession.save(house);
trans.commit();
The way you've coded this confuses hibernate into thinking more things happened than actually did. As suggested in the hibernate manual, I would do something like this:
Code:
House house = new House();
house.setName("White House");
house.setId(10);
Student st1 = new Student();
st1.setId(11);
st1.setName("Ramamani");
house.addStudent(st1);
Student st2 = new Student();
st2.setId(10);
st2.setName("Arumugam");
house.addStudent(st2);
session.save(house);
trans.commit();
Notice the use of an 'addStudent' method, which would look something like this:
Code:
public void addStudent(Student student) {
students.add(student);
student.setHouse(this);
}
The reason you're getting multiple updates is because you've told hibernate to cascade the update operation on House to its associated Students. So when you add the students to the house and save the house, the students will get saved automatically. Calling save again on the students is redundant.