Mapping file
Code:
<class name="MyBean.Child" table="Child">
<id name="id" column="id" type="java.lang.Long">
<generator class="native"/>
</id>
<many-to-one name="Parent" column="parent_id" cascade="save-update"/>
</class>
<class name="MyBean.Parent" table="Parent">
<id name="id" column="id" type="java.lang.Long">
<generator class="native"/>
</id>
<set name="children" cascade="save-update">
<key column="parent_id"/>
<one-to-many class="MyBean.Child"/>
</set>
</class>
Java code
Code:
//Save single parent,child
{
Parent parent = new Parent();
Child child = new Child();
s.save(parent);
s.save(child);
s.flush();
t.commit();
System.out.println("End Save single parent,child");
}
//Save parenty by saving child
{
Child child = new Child();
Parent parent = new Parent();
child.setParent(parent);
s.save(child);
t.commit();
System.out.println("End Save parent by saving child");
}
//Load a parent and add a child
{
Parent parent = (MyBean.Parent)s.load(MyBean.Parent.class,new Long(2));
Child child = new Child();
child.setParent(parent);
parent.getChildren().add(child);
s.update(parent);
t.commit();
System.out.println("End load a parent and add a child");
s.flush();
}
//Dump the children
{
Parent parent = (MyBean.Parent)s.load(MyBean.Parent.class,new Long(2));
Set children = parent.getChildren();
System.out.println(children.size());
//System.out.println( ((MyBean.Child) children.iterator().next()).getId() );
Iterator iterator = children.iterator();
while(iterator.hasNext())
{
Child child = (MyBean.Child) iterator.next();
System.out.println( "Child:" + child.getId() );
}
}
All of the upper codes run smoothly.but when it execute the process named "Dump the children".
It would return the children which was added at the process "Save parenty by saving child" and miss the child added at prcoess "Load a parent and add a child"
I go to the database for searching.There are 2 children matching the parent(id=2).
Why?
If I comment all of the process excep the "Dump the children",and restart the program.It can correctly dump 2 children.
I very confused at the session & transaction.
Does the Hibernate cache the parent object?
or we must close the session first before reload the parent?
Any idea appreciated.