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

Hibernate one-to-one 两方双向连接表关联

阅读更多

  Hibernate中对于持久化实体间的关联关系有三种分类,第一个是一对一,第二个是一对多,第三个是多对多,对于多对一的关联关系认定为是一对多的反向,所以从实质上看这两者是一样的。而对于关联关系的设置,通常的做法是,对于一对一,将关联关系可以放在两方中的任何一方,而对于一对多,将关联关系放置在多方,由多方来控制一对多的关联关系,而对于多对多,需要将关联关系同时放置在两方,即由两方共同来控制多对多的关联关系,不过由于这样的做法带来很大的数据冗余,及其它不合理之处,所以这时会开辟第三张表用来映射多对多的关联关系。那么对于一对多或一对一的关联关系,我想将它们的关联关系用第三张表来表示,应该如何做呢?这就引出来了Hibernate的join的用法,它为我们提供了将一对一或多对多关联关系以第三张表的方式来表示,而不是由关联关系的两方的其中一方去控制。

 

  一。Husband

 

 

package com.dream.model.couple;

/**
 * Created by IntelliJ IDEA.
 * User: Zhong Gang
 * Date: 11-10-15
 * Time: 下午3:53
 */
public class Husband {
    private Integer id;
    private String name;

    private Wife wife;

    public Husband(String name) {
        this.name = name;
    }

    public Husband() {
    }

    public Husband(String name, Wife wife) {
        this.name = name;
        this.wife = wife;
    }

    public Wife wife() {
        return this.wife;
    }
}

 

 

<?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.couple.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"/>

        <join table="couple">
            <key column="husbandid"/>
            <many-to-one name="wife" lazy="false" column="wifeid" class="com.dream.model.couple.Wife" unique="true"
                         cascade="save-update"/>
        </join>
    </class>

</hibernate-mapping>

 

  二。Wife

 

 

package com.dream.model.couple;

/**
 * Created by IntelliJ IDEA.
 * User: Zhong Gang
 * Date: 11-10-15
 * Time: 下午3:52
 */
public class Wife {
    private Integer id;
    private String name;

    private Husband husband;

    public Wife(String name) {
        this.name = name;
    }

    public Wife() {
    }

    public String name() {
        return this.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.couple.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"/>

        <one-to-one name="husband" class="com.dream.model.couple.Husband"/>
    </class>

</hibernate-mapping>

 

  三。CoupleDao

 

 

package com.dream.dao.standard;

import com.dream.model.couple.Husband;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: Zhong Gang
 * Date: 11-10-15
 * Time: 下午4:24
 */
public interface CoupleDao {

    void saveOrUpdateHusband(Husband husband);

    List<Husband> findHusbandsByName(String name);
}

 

 

package com.dream.dao;

import com.dream.dao.standard.CoupleDao;
import com.dream.model.couple.Husband;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: Zhong Gang
 * Date: 11-10-15
 * Time: 下午4:24
 */
public class CoupleDaoImpl extends HibernateDaoSupport implements CoupleDao {

    @Override
    public void saveOrUpdateHusband(Husband husband) {
        getHibernateTemplate().saveOrUpdate(husband);
    }

    @Override
    public List<Husband> findHusbandsByName(String name) {
        return getHibernateTemplate().find("from Husband husband where husband.name=?", name);
    }
}

 

  四。CoupleService

 

 

package com.dream.service.standard;

import com.dream.model.couple.Husband;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: Zhong Gang
 * Date: 11-10-15
 * Time: 下午4:23
 */
public interface CoupleService {

    void saveOrUpdateHusband(Husband husband);

    List<Husband> loadHusbandsByName(String name);
}

 

 

package com.dream.service;

import com.dream.dao.standard.CoupleDao;
import com.dream.model.couple.Husband;
import com.dream.service.standard.CoupleService;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: Zhong Gang
 * Date: 11-10-15
 * Time: 下午4:23
 */
public class CoupleServiceImpl implements CoupleService {

    private CoupleDao coupleDao;

    @Override
    public void saveOrUpdateHusband(Husband husband) {
        coupleDao.saveOrUpdateHusband(husband);
    }

    @Override
    public List<Husband> loadHusbandsByName(String name) {
        return coupleDao.findHusbandsByName(name);
    }

    public void setCoupleDao(CoupleDao coupleDao) {
        this.coupleDao = coupleDao;
    }

}

 

  五。testDB

 

 

db.url=jdbc:mysql://localhost:3306/couple?createDatabaseIfNotExist=true&amp;useUnicode=true&amp;characterEncoding=utf-8

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

 

  六。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>classpath:/hibernate_mappings/Husband.hbm.xml</value>
                <value>classpath:/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="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>

 

   七。Test

 

 

package com.dream.couple;

import com.dream.model.couple.Husband;
import com.dream.model.couple.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.List;

/**
 * Created by IntelliJ IDEA.
 * User: Zhong Gang
 * Date: 11-10-15
 * Time: 下午4:10
 */
public class HibernateJoinTest 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 testOneToOneJoin() throws Exception {

        Wife wife = new Wife("wife");

        Husband husband = new Husband("husband", wife);

        coupleService.saveOrUpdateHusband(husband);
    }

    public void testFindHusband() throws Exception {
        List<Husband> husbands = coupleService.loadHusbandsByName("husband");

        assertEquals(1, husbands.size());

        Husband husband = husbands.get(0);
        Wife wife = husband.wife();
        assertEquals("wife", wife.name());
    }
}

 

  跑完第一个测试,发出的sql语句

 

  test one

 

   跑完第二个测试,发出的sql语句

 

Hibernate: select husband0_.id as id0_, husband0_.name as name0_, husband0_1_.wifeid as wifeid1_ from husband husband0_ inner join couple husband0_1_ on husband0_.id=husband0_1_.husbandid where husband0_.name=?
Hibernate: select wife0_.id as id2_1_, wife0_.name as name2_1_, husband1_.id as id0_0_, husband1_.name as name0_0_, husband1_1_.wifeid as wifeid1_0_ from wife wife0_ left outer join husband husband1_ on wife0_.id=husband1_.id left outer join couple husband1_1_ on husband1_.id=husband1_1_.husbandid where wife0_.id=?
Hibernate: select wife0_.id as id2_1_, wife0_.name as name2_1_, husband1_.id as id0_0_, husband1_.name as name0_0_, husband1_1_.wifeid as wifeid1_0_ from wife wife0_ left outer join husband husband1_ on wife0_.id=husband1_.id left outer join couple husband1_1_ on husband1_.id=husband1_1_.husbandid where wife0_.id=?
 

 

  来看看跑完测试后,数据库中相关的数据表:

 

  result

  • 大小: 30.5 KB
  • 大小: 6 KB
0
2
分享到:
评论

相关推荐

    hibernate的关联映射

    - **中间表关联**:多对多关联通常需要一个中间表来存储两个实体的连接信息。在映射文件中,可以使用`&lt;many-to-many&gt;`标签,指定关联的实体类和中间表的列名。 ```xml &lt;!-- User映射 --&gt; &lt;many-to-many name=...

    Hibernate中的关联映射

    - **有连接表**:类似于多对多映射,但是通过在一方的映射中添加`inverse="true"`来表明该方放弃管理关联关系。 - **映射示例**: - 1端 (`Person`): ```xml &lt;many-to-many class="Address" column=...

    hibrenate xml 配置 映射

    当两个实体通过第三方连接表关联时,可以使用`&lt;join&gt;`标签。连接表通常包含双方主键作为外键。 ```xml &lt;one-to-one name="address" class="com.example.Address" column="address_id"/&gt; ``` #### 2.1.4 一对...

    HIBERNATE - 符合Java习惯的关系数据库持久化

    14. **一对多(One-to-Many)、多对一(Many-to-One)、多对多(Many-to-Many)关系映射**:Hibernate提供了多种关联映射方式,如List、Set、Map等,以适应不同类型的关联关系。 15. **双向关联**:在关联映射中,...

    Hibernate一对一唯一外键关联映射(单向关联)

    在Java的持久化框架Hibernate中,一对一(One-to-One)关联映射是常见的关系数据库模型映射方式之一。本文将详细解析如何实现一对一唯一外键(Uniquely Foreign Key,UFK)关联映射,特别是在单向关联的情况下的具体...

    struts+spring+hibernate资料

    - **一对一 (One-to-One)**:虽然通常推荐使用多对一 (Many-to-One) 替代,但在特定场景下也可以通过 `&lt;one-to-one&gt;` 元素定义。 #### 4. Hibernate 的缓存机制 **内部缓存(一级缓存)**:默认情况下,Hibernate ...

    Spring+Hibernate+Struts工作原理

    类之间的关系通过配置文件中的映射元素(如many-to-one、one-to-many、many-to-many)来定义,如一对一、一对多、多对多的关系映射。 Hibernate还提供了缓存机制,包括一级缓存(SessionFactory级别的缓存,每个...

    java 框架课件

    - 在`Person.hbm.xml`或`Customer.hbm.xml`中,使用`one-to-one`元素定义了`Person`或`Customer`与`Address`之间的关联关系,并且通过`constrained="true"`指定了主键的外键约束。 - `cascade`属性被设置为`all`,...

    struts+spring+Hibernate

    1. **一对一**:可以通过`&lt;one-to-one&gt;` 标签映射两个类之间的一对一关系。 2. **一对多**:使用`&lt;set&gt;` 或 `&lt;list&gt;` 来表示一个类对应多个其他类的实例,通常通过`&lt;one-to-many&gt;` 映射。 3. **多对多**:使用`&lt;many...

    ssh框架面试题

    - **一对一**:使用`&lt;one-to-one&gt;`标签。 - **多对一**:使用`&lt;many-to-one&gt;`标签。 这些关系都是通过配置文件中的标签来定义的,具体取决于实际的需求和设计。 #### 4. Hibernate的缓存机制 - **一级缓存**:...

    Hibernate1:实践

    1. **一对一(One-to-One)映射**: - Hibernate通过在Java实体类中定义一对一关系来实现。这通常通过`@OneToOne`注解完成,它允许我们将一个实体类的实例与另一个实体类的实例关联起来。 - 一对一映射可以是单向...

    javaWEB开发ssh面试题总结

    - **One-to-One(一对一):**两个实体对象之间存在唯一关联。 ### Hibernate缓存机制 **一级缓存:** - **默认启用:**每个Session都会自带一级缓存。 - **生命周期:**随着Session的创建而创建,随着Session的...

    java ee 面试题总结

    - **配置文件中定义**:通过配置文件中的`many-to-one`、`one-to-many`、`many-to-many`标签来指定不同类之间的关系。 #### 四、Hibernate的缓存机制 - **一级缓存(内部缓存)**:每个`Session`都有一个一级缓存...

    Spring 常见面试题

    7. **减少表字段数量**,增加表关联,充分利用二级缓存。 ### Struts 工作机制及其重要性 #### Struts 的工作机制 Struts 是一个基于 MVC 设计模式的框架,主要用于构建 Web 应用。它的核心组件 ActionServlet 在...

    ssh 面试题 全面总结

    1. **一对一**:通常使用`@OneToOne`或`&lt;one-to-one&gt;`标签来表示。 2. **一对多**:使用`@OneToMany`或`&lt;set&gt;`、`&lt;list&gt;`等标签。 3. **多对多**:通过`@ManyToMany`或`&lt;set&gt;`、`&lt;list&gt;`等标签,结合关联表实现。 #...

Global site tag (gtag.js) - Google Analytics