`
Wind_ZhongGang
  • 浏览: 263696 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论
阅读更多

 

 

  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.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: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_fetch

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

 

  七。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;

    @Override
    public 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=?

   all-delete-orphan

 

  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=?

   save-update

  • 大小: 2.4 KB
  • 大小: 4.8 KB
0
0
分享到:
评论

相关推荐

    Hibernate关联关系(一对多)

    ### Hibernate关联关系(一对多) #### 一、概念与背景 在软件开发中,尤其是在数据库设计及ORM(对象关系映射)技术的应用中,“一对多”关系是非常常见的一种数据关联方式。例如,一个班级可以拥有多个学生,但每...

    Hibernate多对多关联关系demo

    在Java的持久化框架Hibernate中,多对多(Many-to-Many)关联关系是一种常见的实体间关系类型,它表示一个实体可以与多个其他实体相关联,反之亦然。本示例"Hibernate多对多关联关系demo"将深入探讨如何在实际开发中...

    Hibernate 一对一关联查询.docx

    - 在拥有外键的一方(如User),可以自由地维护关联关系,包括建立、修改和解除。 - 可以随意删除拥有外键的对象,如果在映射文件中设置了`cascade="delete"`,删除User时,其关联的IdCard也会被删除。 - 没有外键的...

    Hibernate教程14_关系映射之多对多双向关联

    本教程将重点讲解如何在Hibernate中实现多对多双向关联,这是数据库设计中常见的一种关系类型,它允许一个实体实例与多个其他实体实例相互关联。 在数据库设计中,多对多关系意味着一个表的记录可以与另一个表的多...

    Java开源项目Hibernate深度探险

    Hibernate能够自动处理这些关联的建立和解除,使得对象间的操作更加自然。 四、Hibernate的高级特性 除了基本的对象关系映射,Hibernate还提供了许多高级特性,包括: 1. **缓存机制**:Hibernate支持一级缓存...

    hibernate 多对多源代码

    在Java的持久化框架Hibernate中,多对多(Many-to-Many)关系是数据库中常见的关联类型,它允许一个实体实例对应多个其他实体实例,反之亦然。本篇将深入探讨Hibernate如何处理这种复杂的数据关联。 一、多对多关系...

    Hibernate cascade (级联).doc

    通常用于一对多或多对多的关系中,当一个实体与另一个实体解除关联时,若解除关联的对象没有其他实体关联,则会自动删除该对象。 6. **all-delete-orphan**:这个级联选项结合了 all 和 delete-orphan 的行为。它...

    hibernate 双向一对一基于外键的关联映射

    在Java世界中,Hibernate是一个非常流行的ORM(对象关系映射)框架,它允许开发者使用面向对象的方式来处理数据库操作。在数据库关系模型中,一对一(OneToOne)关联是一种常见的关系类型,表示两个实体之间存在唯一...

    hibernate_配置cascade_及all-delete-orphan.doc

    - 如果希望在解除关系的同时删除子实体,则需要显式地设置`cascade`属性为`all-delete-orphan`,并添加相应的配置: ```xml ``` 这样,在运行时会执行: ```sql DELETE FROM ORDERS WHERE CUSTOMER_ID...

    hibernate一对多实例

    在这个“hibernate一对多实例”中,我们将深入探讨如何在Hibernate中实现一对多的关系,这是一种常见的关联类型,其中一方实体可以与多方实体相对应。 一、Hibernate一对多关系 在数据库设计中,一对多关系表示一...

    hibernate_1700_one2many_many2one_bi_crud(5)

    通常,需要先解除关联关系,然后再删除。 在压缩包中的“hibernate_1400_one2many_many2one_uni”文件可能包含了关于单向一对多(One-to-Many)和多对一关联的例子。单向关联只在一个方向上有引用,而双向关联在两...

    Hibernate三种状态区分

    Hibernate 是一个流行的 Java ORM(对象关系映射)框架,它允许开发者以面向对象的方式操作数据库。在 Hibernate 中,对象有三种不同的状态,这些状态决定了对象与数据库之间的关联程度以及如何进行数据操作。理解...

    Hibernate 删除出现异常的解决方案.doc

    例如,在一对多关系中,如果有对象one与对象many关联,可以先调用`one.getManys().remove(thisMany)`将many从one的集合中移除,然后设置`thisMany.setOne(null)`来解除关联,最后通过many的DAO层执行`manyDao.delete...

    hibernate压缩包

    9. **关联映射**:Hibernate支持一对一、一对多、多对一、多对多等各种关联关系,通过`@OneToOne`, `@OneToMany`, `@ManyToOne`, `@ManyToMany`等注解进行配置。 10. **性能优化**:包括批处理、延迟加载、预加载、...

    十五道Hibernate面试题及答案.doc

    在这个例子中,Customer对象在第19行session1.close()之后变为游离状态,因为Session被关闭,对象与Session的关联解除。 这些面试题涵盖了Hibernate的基础知识,包括对象关系映射、SessionFactory的使用、集合映射...

    Hibernate(23):一个较为复杂些的例子

    - 删除:删除`Role`或`Right`时,需要确保已解除它们之间的关联,否则可能导致数据不一致。 4. **工具使用**: - Hibernate Tools:这是一套用于生成映射文件、持久化类以及数据库脚本的工具,可以帮助快速搭建...

    Hibernate 参考文档

    通过提供一套API和元数据接口,Hibernate 解除了传统Java应用程序与SQL之间的耦合,使得开发人员可以更专注于业务逻辑,而无需过多地关心底层数据库操作。 **安装与配置** 在使用Hibernate之前,需要将其添加到...

Global site tag (gtag.js) - Google Analytics