cascade="save-update" 与 inverse="true"使用讲解(回钦波)
今天在hibernate-hbm.xml里面做了调试发现casecade 和 inverse 的用法所在:
?
?
1.
?
public class FlowForm {?
?
public class FormField {?
?测试:
?
Session session = null;?
配置文件:
1.
?
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
? <class table="T_FormField" name="com.nqyw.oa.model.FormField">
??? <id name="id">
????? <generator name="items">
?????? <key column="formfieldId"></key>
?????? <list-index column="itemIndex"></list-index>
?????? <composite-element encoding="ISO-8859-1"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
? <class table="T_FlowForm" name="com.nqyw.oa.model.FlowForm">
??? <id name="id">
????? <generator cascade="save-update"? name="fields">
??????? <key column="flowformId"></key>
??????? <one-to-many 和 inverse="true" ,表示我父(FlowForm.java)爸爸要负责维护子的关系,
SQL语句是:
Hibernate: insert into T_FormField (fieldName, fieldLabel, fieldType, fieldInput, flowForm) values (?, ?, ?, ?, ?)
Hibernate: insert into T_FormField (fieldName, fieldLabel, fieldType, fieldInput, flowForm) values (?, ?, ?, ?, ?)
Hibernate: insert into T_FormField (fieldName, fieldLabel, fieldType, fieldInput, flowForm) values (?, ?, ?, ?, ?)
Hibernate: insert into T_FormField (fieldName, fieldLabel, fieldType, fieldInput, flowForm) values (?, ?, ?, ?, ?)
如果没有cascade="save-update",的话,保存父(FlowForm.java)时 子类(FormField.java)是不能被保存的。
?
?
------------------------------------------------------
如果有 :cascade="save-update"?而没有?inverse="true" ,表示我父(FlowForm.java)爸爸要负责维护子的关系,
SQL语句是:
Hibernate: insert into T_FlowForm (template) values (?)
Hibernate: insert into T_FormField (fieldName, fieldLabel, fieldType, fieldInput, flowForm) values (?, ?, ?, ?, ?)
Hibernate: insert into T_FormField (fieldName, fieldLabel, fieldType, fieldInput, flowForm) values (?, ?, ?, ?, ?)
Hibernate: insert into T_FormField (fieldName, fieldLabel, fieldType, fieldInput, flowForm) values (?, ?, ?, ?, ?)
Hibernate: insert into T_FormField (fieldName, fieldLabel, fieldType, fieldInput, flowForm) values (?, ?, ?, ?, ?)
Hibernate: update T_FormField set flowformId=? where id=?
Hibernate: update T_FormField set flowformId=? where id=?
Hibernate: update T_FormField set flowformId=? where id=?
Hibernate: update T_FormField set flowformId=? where id=?
多了四条是因为父类这边在添加完父子下,还要更新管理下子类。所以最好加上??inverse="true"。这样会提高效率
如果没有cascade="save-update",的话,保存父(FlowForm.java)时 子类(FormField.java)是不能被保存的。