When I using hibernate update talbe,the parent table can be updated succesful,but the child table only do insert,can't update the old records
Parent.hbm.xml
Code:
<hibernate-mapping>
<class name="com.websh.hibernate.model.Parent" table="parent" dynamic-update="true" dynamic-insert="true">
<id column="parentid" name="parentid" type="java.lang.Long">
<generator class="increment"/>
</id>
<property column="parentname" length="50" name="parentname" type="java.lang.String"/>
<bag name="childs" cascade="all" inverse="true" >
<key column="parentid"/>
<one-to-many class="com.websh.hibernate.model.Child"/>
</bag>
</class>
</hibernate-mapping>
Child.hbm.xml
Code:
<hibernate-mapping>
<class name="com.websh.hibernate.model.Child" table="child" dynamic-update="true" dynamic-insert="true">
<id column="childid" name="childid" type="java.lang.Long">
<generator class="increment"/>
</id>
<property column="childname" length="50" name="childname" type="java.lang.String"/>
<many-to-one name="parent" class="com.websh.hibernate.model.Parent" not-null="true" column="parentid"/>
</class>
</hibernate-mapping>
Child.java
Code:
public Parent getParent() {
return parent;
}
public void setParent(Parent parent) {
this.parent = parent;
}
Parent.java
Code:
public Collection getChilds() {
if (childs==null){
childs = new ArrayList();
}
return this.childs;
}
public void setChilds(Collection childs) {
for (Iterator iter = childs.iterator(); iter.hasNext(); ) {
Child item = (Child)iter.next();
item.setParent(this);
}
this.childs = childs;
}
method
Code:
public static void update(){
Collection col = new ArrayList();
try{
Configuration cfg = new Configuration().configure();
SessionFactory sessions = cfg.buildSessionFactory();
Session session = sessions.openSession();
Transaction tx = session.beginTransaction();
Child c = new Child();
for (int i = 0; i < 3; i++) {
c.setChildname("儿子up"+i);
col.add(c);
}
Parent p = new Parent();
p = (Parent)session.load(Parent.class, new Long(1));
p.setChilds(col);
p.setParentname("a");
session.update(p);
session.flush();
tx.commit();
session.close();
}catch(Exception e){
e.printStackTrace();
}
}