对于Hibernate的one-to-many关联关系中,合理使用cascade属性能够显著减少代码量,减轻程序员的工作量。
一。Husband
package com.hibernate; import java.util.Set; /** * Created by IntelliJ IDEA. * User: Zhong Gang * Date: 9/7/11 * Time: 2:22 PM */ public class Husband { private Integer id; private String name; private Set<Wife> wifes; public Husband() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set<Wife> getWifes() { return wifes; } public void setWifes(Set<Wife> wifes) { this.wifes = wifes; } }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping default-access="field"> <class name="com.hibernate.Husband" table="husband" dynamic-insert="true" dynamic-update="true"> <id name="id" column="id" type="java.lang.Integer"> <generator class="native"/> </id> <property name="name" column="name" type="java.lang.String"/> <set name="wifes"> <key column="husbandid"/> <one-to-many class="com.hibernate.Wife"/> </set> </class> </hibernate-mapping>
二。Wife
package com.hibernate; /** * Created by IntelliJ IDEA. * User: Zhong Gang * Date: 9/7/11 * Time: 2:22 PM */ public class Wife { private Integer id; private String name; private Husband husband; public Wife() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Husband getHusband() { return husband; } public void setHusband(Husband husband) { this.husband = husband; } }
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping default-access="field"> <class name="com.hibernate.Wife" table="wife" dynamic-insert="true" dynamic-update="true"> <id name="id" column="id" type="java.lang.Integer"> <generator class="native"/> </id> <property name="name" column="name" type="java.lang.String"/> <many-to-one name="husband" column="husbandid" class="com.hibernate.Husband" cascade="save-update"/> </class> </hibernate-mapping>
三。db.properties and testDatasource.xml
db.url=jdbc:mysql://localhost:3306/dream db.driver=com.mysql.jdbc.Driver db.username=root db.password=root hibernate.dialect=org.hibernate.dialect.MySQL5Dialect hibernate.show_sql=true hibernate.hbm2ddl.auto=update hibernate.jdbc.batch_size=100
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd" default-autowire="byName"> <context:property-placeholder location="classpath:db.properties"/> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${db.driver}"/> <property name="url" value="${db.url}"/> <property name="username" value="${db.username}"/> <property name="password" value="${db.password}"/> </bean> <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="mappingLocations"> <list> <value>classpath:/hibernate_mappings/*</value> </list> </property> <property name="hibernateProperties"> <props> <prop key="hibernate.dialect">${hibernate.dialect}</prop> <prop key="hibernate.show_sql">${hibernate.show_sql}</prop> <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> <prop key="hibernate.jdbc.batch_size">${hibernate.jdbc.batch_size}</prop> </props> </property> </bean> <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/> </bean> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="*" propagation="REQUIRED"/> </tx:attributes> </tx:advice> <aop:config> <aop:pointcut id="service" expression="execution(* com.hibernate..*.*(..))"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="service"/> </aop:config> </beans>
四。HibernateCascadeTest
package com.hibernate; import junit.framework.TestCase; import org.hibernate.SessionFactory; import org.hibernate.classic.Session; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import java.util.HashSet; import java.util.Set; /** * Created by IntelliJ IDEA. * User: Zhong Gang * Date: 9/7/11 * Time: 2:43 PM */ public class HibernateCascadeTest extends TestCase { public void testDelete() throws Exception { ApplicationContext context = new ClassPathXmlApplicationContext("testDatasource.xml"); SessionFactory sessionFactory = (SessionFactory) context.getBean("sessionFactory"); Session session = sessionFactory.openSession(); Husband husband = new Husband(); husband.setName("Husband"); Wife wife1 = new Wife(); wife1.setName("Wife 1"); wife1.setHusband(husband); Wife wife2 = new Wife(); wife2.setName("Wife 2"); wife2.setHusband(husband); Set<Wife> wifes = new HashSet<Wife>(); wifes.add(wife1); wifes.add(wife2); husband.setWifes(wifes); session.saveOrUpdate(wife1); session.saveOrUpdate(wife2); session.flush(); session.delete(wife1); session.flush(); } }
理解cascade级联操作:当对实体进行CRUD操作时,对其配置文件中的配置有cascade的属性的实体是否也应该执行该操作。如当对Husband实体进行保存时,如果此时在Husband.hbm.xml配置文件中,对Wife的实体配置cascade="save-update",表明当对Husband进行保存或修改时,也会引起对与Husband实体相关的Wife的实体的保存或修改操作。cascade有这样几种常用值,save-update,delete,all等。delete表明只有进行删除操作,才会引起级联删除操作,而all则表明对实体进行CRUD操作时,会引起cascade的实体的CRUD操作。具体配置哪种值,可根据项目中的实际需要,具体需求,具体分析。
那么对于一个one-to-many的实体关联关系,应该将cascade配置在一方还是多方呢?我的建议是配置在一方。试想,对于上述举例,如果在Husband.hbm.xml中的wifes属性上配置 cascade="all",那么当添加或修改Husband实体时,会相应地引起对于Wife的级联添加或修改操作,而如果删除Husband实体,因为该实体在数据库中已不存在,那么再在Wife实体中的Husband维护这样的一对多关系,完全是没有任何必要的。而如果在Wife.hbm.xml中的husband属性上配置cascade="all",那么当保存或修改Wife实体时,会级联保存或修改Husband实体,而当删除Wife实体时,会级联删除Husband实体,这样Hibernate是会报错的,原因很简单,一个Husband关联着多个Wife,当删除其中一个Wife时,就去删除Husband,那么其它的Wife的Husband不就找不到对应的实体了嘛,所以在多方配置cascade="all"或cascade="all-delete-orphan",cascade="delete",不仅导致系统错误,在现实需求中来说也是绝对不允许的。