Hi,
I am newbie,one problem always bothers my head recently,that is using set tag represent parent/child
relationship. before use set tag i always used bag tag, it worked fine,but effect was not good. so i
decide to use set tag to represent parent/child relationship for effect. but the result is not what i
expected,can anybody tell me what my miss is?
Thanks in advance.
class Parent implements Serialiable{
private int id;
private Set children=new TreeSet();
public int getId(){
return id;
}
public void setId(int id){
this.id=id;
}
public int getChildren(){
return children;
}
public void setChildren(Set children){
this.children=children;
}
public toString equals(Object other){
.........
}
public String toString(){
........
}
public int hashCode(){
........
}
}
class Child implements Serializable,Comparable{
private int id;
private String name=null;
private Parent parent=null;
public int getId(){
return id;
}
public void setId(int id){
this.id=id;
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public Parent getParent(){
return parent;
}
public void setParent(Parent parent){
this.parent=parent;
}
public toString equals(Object other){
.........
}
public String toString(){
........
}
public int hashCode(){
........
}
public int compareTo(Object obj){
return -1;
}
}
Parent.xml
.......
<id name="id" column="id" type="int" unsaved-value="0">
<generator class="identity"/>
</id>
<property name="name" column="name" type="string" length="100"/>
<set name="Childs" inverse="false" cascade="all" lazy="true" sort="natural">
<key column="collgeId"/>
<one-to-many class="bean.Child"/>
</set>
.............
Child.xml
.............
<id name="id" column="id" type="int" unsaved-value="0">
<generator class="identity"/>
</id>
<property name="name" column="name" type="string" length="100"/>
<many-to-one name="parent" class="bean.Parent" column="collgeId" not-null="true"/>
..................
code:
session=sessionFactory.openSession();
Parent p=(Parent)session.get(Parent.class,new Integer(1));
Set set=p.getChildren();
Child c1=new Child();
c1.setName("Tom 1");
c1.setParent(c);
set.add(c1);
Child c2=new Child();
c2.setName("Tom 2");
c2.setParent(c);
set.add(c2);
session.flush();
session.close();
My DB is MySql4.0,PlatForm is WinXP.
1.When set tag in parent.xml has attribute sort="natural", result as below:
after executed 1 time:
id name parent_id
1 Tom 1 1
2 Tom 2 1
after executed 2 times:
id name parent_id
1 Tom 1 Null
2 Tom 2 Null
3 Tom 1 1
4 Tom 2 1
why is this?
2.when set hasn't sort="natural", result as below:
after executed 1 time:
id name parent_id
1 Tom 1 1
after executed 2 times:
id name parent_id
1 Tom 1 1
2 Tom 1 1
only the first record is inserted,why?
any help for appreciate.
|