当前位置: 代码迷 >> Java Web开发 >> Hibernate,级联保存为何无效?
  详细解决方案

Hibernate,级联保存为何无效?

热度:3649   发布时间:2013-02-25 21:09:02.0
Hibernate,级联保存为什么无效??
有两个表分别是Customers和Orders,它们是一对多的关系,它们的*.hbm.xml文件分别是
Customer.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
"-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">

<hibernate-mapping package="org.pojo">
  <class name="Customer" table="CUSTOMERS" dynamic-insert="true" dynamic-update="true" >
  <id name ="id" column ="ID" type="integer">
  <generator class="sequence">  
  <param name="sequence">seq_id</param>  
  </generator>  
  </id>
   
  <property name="name" column="NAME" type="string" not-null="true"></property> 
  <property name="sex" access="field"></property>
   
  <set name="orders" 
  inverse="true"
  cascade="save-update">
  <key column="CUSTOMER_ID"></key>
  <one-to-many class="org.pojo.Order"/>
  </set>
   
  <property name="totalPrice" formula=" (select sum(o.price) from ORDERS o where o.CUSTOMER_ID=ID)"/>
  <property name="description" column="DESCRIPTION" type="text"></property>  
  </class> 
</hibernate-mapping>

Order.hbm.xml文件为
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC 
"-//Hibernate/Hibernate Mapping DTD 2.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">

<hibernate-mapping package="org.pojo">
  <class name="Order" dynamic-insert="true" dynamic-update="true" >
  <id name ="id" column ="ID" type="integer">
  <generator class="sequence" >  
  <param name="sequence">seq_order_id</param>
  </generator>  
  </id>
   
  <property name="orderNumber" column="ORDER_NUMBER" type="string" ></property> 
  <property name="price"></property>  
   
  <many-to-one name="customer" class="org.pojo.Customer" >
  <column name="CUSTOMER_ID"></column>
  </many-to-one>
  </class>
 
</hibernate-mapping>
因为我在Customer.hbm.xml的<set>中设置了cascade="save-update",理论上在新增Customer时应该级联保存Order的,
但发现Customer能保存,Order无法保存。程序也没报错。我看到控制台上对于Customers表是打印了insert语句,
但对于Orders表,打印的是update语句。为什么不是insert语句?为什么级联无法保存Order?

Customer customer = new Customer("LiShi","Lin",'M',new HashSet(),null);
Order order1 = new Order("Order0001",100.0,customer );
customer_1.getOrders().add(order1);
saveCustomer_1(customer);

在持久类的Customer也设置有Order的setter/getter了。

------解决方案--------------------------------------------------------
<set name="orders" 
inverse="true" 
cascade="save-update"> 
<key column="CUSTOMER_ID"> </key> 
  相关解决方案