Hibernate对于持久化实体间的关联关系解除,有两种实现方式,一种是将关联关系实体中彻底删除,而另一种则是将关联关系的外键值设为空,即NULL。两种方式在配置文件中的体现为为cascade设置不同的值。

  一。Husband

package com.dream.model.join;import java.util.Set;/*** Created by IntelliJ IDEA.* User: Zhong Gang* Date: 9/26/11* Time: 5:46 PM*/
public class Husband {private Integer id;private String name;private Set<Wife> wifes;public Husband(String name) {this.name = name;}public Husband() {}public Husband(String name, Set<Wife> wifes) {this.name = name;this.wifes = wifes;}public Set<Wife> getWifes() {return wifes;}public Integer getId() {return id;}public String getName() {return name;}public void setName(String name) {this.name = name;}
}
<?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.dream.model.join.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" table="wife" cascade="all-delete-orphan"><key column="husbandid"/><one-to-many class="com.dream.model.join.Wife"/></set></class></hibernate-mapping>

  二。Wife

package com.dream.model.join;/*** Created by IntelliJ IDEA.* User: Zhong Gang* Date: 9/26/11* Time: 5:47 PM*/
public class Wife {private Integer id;private String name;private Husband husband;public Wife(String name) {this.name = name;}public Wife() {}public Wife(String name, Husband husband) {this.name = name;this.husband = husband;}public String getName() {return name;}public Husband getHusband() {return 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.dream.model.join.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" class="com.dream.model.join.Husband" column="husbandid"/></class></hibernate-mapping>

  三。CoupleDao

package com.dream.dao.standard;import com.dream.model.join.Husband;
import com.dream.model.join.Wife;import java.util.Set;/*** Created by IntelliJ IDEA.* User: Zhong Gang* Date: 9/26/11* Time: 5:51 PM*/
public interface CoupleDao {Husband findHusbandById(Integer id);void saveOrUpdateHusband(Husband husband);void deleteHusband(Husband husband);
}
package com.dream.dao;import com.dream.dao.standard.CoupleDao;
import com.dream.model.join.Husband;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;import java.util.List;/*** Created by IntelliJ IDEA.* User: Zhong Gang* Date: 9/26/11* Time: 5:52 PM*/
public class CoupleDaoImpl extends HibernateDaoSupport implements CoupleDao {public Husband findHusbandById(Integer id) {List<Husband> husbands = getHibernateTemplate().find("from Husband husband where husband.id=?", id);if (husbands.isEmpty()) {return null;}return husbands.get(0);}public void saveOrUpdateHusband(Husband husband) {getHibernateTemplate().saveOrUpdate(husband);}public void deleteHusband(Husband husband) {getHibernateTemplate().delete(husband);}
}

  四。CoupleService

package com.dream.service.standard;import com.dream.model.join.Husband;/*** Created by IntelliJ IDEA.* User: Zhong Gang* Date: 9/26/11* Time: 5:53 PM*/
public interface CoupleService {Husband loadHusbandById(Integer id);void saveOrUpdateHusband(Husband husband);void deleteHusbandById(Integer id);
}
package com.dream.service;import com.dream.dao.standard.CoupleDao;
import com.dream.exception.DataNotExistException;
import com.dream.model.join.Husband;
import com.dream.service.standard.CoupleService;/*** Created by IntelliJ IDEA.* User: Zhong Gang* Date: 9/26/11* Time: 5:53 PM*/
public class CoupleServiceImpl implements CoupleService {private CoupleDao coupleDao;public Husband loadHusbandById(Integer id) {Husband husband = coupleDao.findHusbandById(id);if (husband == null) {throw new DataNotExistException();}return husband;}public void saveOrUpdateHusband(Husband husband) {coupleDao.saveOrUpdateHusband(husband);}public void deleteHusbandById(Integer id) {Husband husband = coupleDao.findHusbandById(id);coupleDao.deleteHusband(husband);}public void setCoupleDao(CoupleDao coupleDao) {this.coupleDao = coupleDao;}
}
package com.dream.exception;/*** Created by IntelliJ IDEA.* User: Zhong Gang* Date: 9/26/11* Time: 6:01 PM*/
public class DataNotExistException extends RuntimeException {public DataNotExistException() {super("The data you find does not exist in the database.");}
}

  五。testDatasource

<?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.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"default-autowire="byName"><context:property-placeholder location="classpath:testDB.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>/hibernate_mappings/Husband.hbm.xml</value><value>/hibernate_mappings/Wife.hbm.xml</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.dream.service..*.*(..))"/><aop:advisor advice-ref="txAdvice" pointcut-ref="service"/></aop:config><bean id="coupleDao" class="com.dream.dao.CoupleDaoImpl"><property name="sessionFactory" ref="sessionFactory"/></bean><bean id="coupleService" class="com.dream.service.CoupleServiceImpl"><property name="coupleDao" ref="coupleDao"/></bean>
</beans>

  六。testDB

db.url=jdbc:mysql://localhost:3306/test_fetchdb.driver=com.mysql.jdbc.Driverdb.username=rootdb.password=roothibernate.dialect=org.hibernate.dialect.MySQL5Dialecthibernate.show_sql=truehibernate.hbm2ddl.auto=updatehibernate.jdbc.batch_size=100

  七。TestCase

package com.fetch;import com.dream.model.join.Husband;
import com.dream.model.join.Wife;
import com.dream.service.standard.CoupleService;
import junit.framework.TestCase;
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/26/11* Time: 6:05 PM*/
public class HibernateCascadeTest extends TestCase {private CoupleService coupleService;@Overridepublic void setUp() throws Exception {ApplicationContext context = new ClassPathXmlApplicationContext("classpath:testDatasource.xml");coupleService = (CoupleService) context.getBean("coupleService");}public void testCascadeAllDelete() throws Exception {Wife wife1 = new Wife("Wife1");Wife wife2 = new Wife("Wife2");Set<Wife> wifes = new HashSet<Wife>();wifes.add(wife1);wifes.add(wife2);Husband husband = new Husband("Husband1", wifes);coupleService.saveOrUpdateHusband(husband);coupleService.deleteHusbandById(husband.getId());}
}

  Scenario 1:cascade="all-delete-orphan" in Husband.hbm.xml

Hibernate: insert into husband (name) values (?)
Hibernate: insert into wife (name) values (?)
Hibernate: insert into wife (name) values (?)
Hibernate: update wife set husbandid=? where id=?
Hibernate: update wife set husbandid=? where id=?
Hibernate: select husband0_.id as id0_, husband0_.name as name0_ from husband husband0_ where husband0_.id=?
Hibernate: select wifes0_.husbandid as husbandid0_1_, wifes0_.id as id1_, wifes0_.id as id1_0_, wifes0_.name as name1_0_, wifes0_.husbandid as husbandid1_0_ from wife wifes0_ where wifes0_.husbandid=?
Hibernate: update wife set husbandid=null where husbandid=?
Hibernate: delete from wife where id=?
Hibernate: delete from wife where id=?
Hibernate: delete from husband where id=?

  

  Scenario 2:cascade="all" in Husband.hbm.xml

  结论同上

  Scenario 3:cascade="delete" in Husband.hbm.xml

  结论同上

  Scenario 4:cascade="delete-orphan" in Husband.hbm.xml

  结论同上

  Scenario 5:cascade="save-update" in Husband.hbm.xml

Hibernate: insert into husband (name) values (?)
Hibernate: insert into wife (name) values (?)
Hibernate: insert into wife (name) values (?)
Hibernate: update wife set husbandid=? where id=?
Hibernate: update wife set husbandid=? where id=?
Hibernate: select husband0_.id as id0_, husband0_.name as name0_ from husband husband0_ where husband0_.id=?
Hibernate: update wife set husbandid=null where husbandid=?
Hibernate: delete from husband where id=?

  

Hibernate 关联关系解除相关推荐

  1. Hibernate 关联关系 之 多对多

    Hibernate 关联关系 之 多对多 Hibernate 多对多关联关系 数据库表 entity 实体类 Book Category TreeNode xml 配置 book.hbm.xml ca ...

  2. Hibernate关联关系映射

    1.  Hibernate关联关系映射 1.1.  one to one <class name="Person"> <id name="id" ...

  3. Hibernate关联关系映射实例速查

    Hibernate关联关系映射实例速查 Hibernate的映射关系很多,也比较复杂,也很容易忘记.这个基本上占据了Hibernate学习的七成时间.熟悉这些映射模型,需要大量的实践才能掌握.下面是我 ...

  4. hibernate关联关系笔记

    Hibernate关联关系笔记 单向N:1 *  有连接表:在N方使用<join>/<many-to-one>.1方无需配置与之关联的持久化类. *  没有连接表:在N方使用& ...

  5. hibernate关联关系(多对多)

    一.一对多自关联实例: 数据库表 t_hibernate_sys_tree_node: 实体类 TreeNode: package com.liuwenwu.four.entity;import ja ...

  6. Hibernate关联关系映射之一对一关联关系

    人和身份证之间就是一个典型的一对一关联关系.实现一对一关联关系映射的方式有两种一种是基于外键,一种是基于主键,下面我们先看基于外键的关联方式 首先看他们的实体类 Person类 ? 1 2 3 4 5 ...

  7. Hibernate关联关系配置(一对多,一对一,多对多)

    一对多 创建两个类  Manager(一这一端) Worker(多这一端)  即一个经理下有多个员工 package com.hibernate.n21;import java.util.HashSe ...

  8. hibernate关联关系(一对多)

    什么是关联(association) 关联指的是类之间的引用关系.如果类A与类B关联,那么被引用的类B将被定义为类A的属性.例如: class B{private String name;}publi ...

  9. Hibernate关联关系映射-----双向一对多/多对一映射配置

    转自:http://blog.csdn.net/yifei12315/article/details/6985194 /// Hibernate: /// 双向关联就是有"一对多" ...

最新文章

  1. winsock I/O模型
  2. Java数组对象的内存布局
  3. 哔哩哔哩swot分析_哔哩哔哩2020校园招聘游戏运营笔试真题
  4. C#中如何控制播放音乐的声音大小
  5. python爬虫框架scrapy操作步骤
  6. makefile指定头文件路径_玩转Makefile | 企业项目Makefile实例
  7. 谷歌浏览器设置请求头_2020年 谷歌SEO优化 十大技巧(四)
  8. jquery 左右移动 以及使用layer.js弹出框呈现在页面上
  9. JavaScript学习指南 (来自转载)
  10. web前端简历个人技能该怎么写?
  11. 前端面试谈:项目经历的 STAR 法则
  12. ime输入法android,创建输入法  |  Android 开发者  |  Android Developers
  13. Python实用技巧 使用pillow库批量修改文件夹下所有PNG图片透明度
  14. 游戏密码123456问题
  15. 修改Mac 共享Wifi默认的桥接IP
  16. 飞塔防火墙虚拟服务器,飞塔防火墙模拟(1):模拟器使用方法 | 网络之路博客(公众号同名)(其他平台网络之路Blog)...
  17. 【笨木头Unity】入门之旅007:Demo之四处找死(二)_主角移动和旋转
  18. css3制作八棱锥_CSS 绘制各种形状
  19. TCP/IP参考模型-分层架构
  20. IPFS直播最详细解读—FileCoin Demo演示

热门文章

  1. 2021年,学UI设计还吃香吗?
  2. 【Android】App开发-动画效果篇
  3. python编程:从入门到实践 阅读笔记
  4. 平安证券最新股票池强荐4只股
  5. Chrome浏览器 设置跨域访问
  6. java 获取 yyyymmdd_从JS日期对象获取YYYYMMDD格式的字符串?
  7. 人工智能AI程序设计语言
  8. 2020-05-11
  9. php 实现我的足迹,Wordpress 实现“您的足迹”功能
  10. 用U盘打造专属个人的微型护航系统--winpe