Hibernate fetch 캡 처 정책

18841 단어 Hibernatefetch

Hibernate fetch 캡 처 정책 은 관련 대상 을 캡 처 할 때 어떤 방식 으로 캡 처 하 는 지 정의 합 니 다.캡 처 정책 이 join 일 때 캡 처 대상 은 연결 표를 통 해 캡 처 됩 니 다. sql 문 구 를 보 내 면 주 대상 과 관련 대상 의 캡 처 를 완성 할 수 있 습 니 다. 캡 처 정책 이 select 일 때 관련 대상 을 캡 처 할 때 두 개의 sql 문 구 를 보 내 관련 이미지 캡 처 를 완성 합 니 다. 하 나 는 주 대상 을 캡 처 하 는 것 이 고 다른 하 나 는 관련 대상 을 캡 처 하 는 것 입 니 다.캡 처 정책 은 보통 로드 지연 정책 과 합 쳐 사용 합 니 다. 이 는 로드 지연 정책 을 사용 할 때 캡 처 정책 의 설정 이 적당 하지 않 으 면 상상 밖의 이상 을 초래 할 수 있 기 때 문 입 니 다. 비 지연 로드 정책 을 사용 할 때 즉시 로드 정책 입 니 다. 일반적인 제안 은 join 즉 연결 캡 처 정책 을 사용 하여 데이터 베이스 에 여러 개의 sql 문 구 를 보 내 는 것 을 피 하 는 것 입 니 다.주의해 야 할 것 은 get 이나 load 방법 으로 대상 을 가 져 올 때 만 캡 처 정책 이 작 동 합 니 다. 대상 을 찾 을 때 사용자 정의 hql 이나 sql 문 구 를 사용 하면 캡 처 정책 이 작 동 하지 않 습 니 다.그 중에서 get 방법 은 즉시 로드 대상 이 고 load 는 로드 지연 대상 이 며 이 대상 을 사용 할 때 만 데이터베이스 에 조회 문 구 를 보 내 이 대상 을 찾 을 수 있 습 니 다.
 
하나.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" lazy="false" fetch="join">
            <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);

}

 
 
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) {
         return getHibernateTemplate().get(Husband.class, id);
    }

    public void saveOrUpdateHusband(Husband husband) {
        getHibernateTemplate().saveOrUpdate(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);
}
 
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 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 HibernateFetchTest 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);

        Husband husbandAfterFound = coupleService.loadHusbandById(husband.getId());
        Set<Wife> wifeSet = husbandAfterFound.getWifes();
        assertEquals(2, wifeSet.size());
    }
}

 
  Scenario 1:lazy="true" fetch="join"
  
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_1_, husband0_.name as name0_1_, wifes1_.husbandid as husbandid0_3_, wifes1_.id as id3_, wifes1_.id as id1_0_, wifes1_.name as name1_0_, wifes1_.husbandid as husbandid1_0_ from husband husband0_ left outer join wife wifes1_ on husband0_.id=wifes1_.husbandid where husband0_.id=?

sql 문 구 를 한 개 만 보 내 고 주 대상 과 관련 대상 을 찾 아 냈 습 니 다.
 
  Scenario 2:lazy="true" fetch="select"
  
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_0_, husband0_.name as name0_0_ from husband husband0_ where husband0_.id=?

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.dream.model.join.Husband.wifes, no session or session was closed
	at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:383)
	at org.hibernate.collection.AbstractPersistentCollection.throwLazyInitializationExceptionIfNotConnected(AbstractPersistentCollection.java:375)
	at org.hibernate.collection.AbstractPersistentCollection.readSize(AbstractPersistentCollection.java:122)
	at org.hibernate.collection.PersistentSet.size(PersistentSet.java:162)
	at com.fetch.HibernateFetchTest.testCascadeAllDelete(HibernateFetchTest.java:42)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at com.intellij.junit3.JUnit3IdeaTestRunner.doRun(JUnit3IdeaTestRunner.java:139)
	at com.intellij.junit3.JUnit3IdeaTestRunner.startRunnerWithArgs(JUnit3IdeaTestRunner.java:52)
	at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:199)
	at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:62)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
	at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

 지연 로드 정책 을 사용 하 는 동시에 select 캡 처 정책 을 사용 할 때 대상 이 사용 할 때 만 sql 문 구 를 시작 할 수 있 기 때문에 session 관리 가 없 기 때문에 이상 이 발생 할 수 있 습 니 다.
  Scenario 3:lazy="false" fetch="join"
  
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_1_, husband0_.name as name0_1_, wifes1_.husbandid as husbandid0_3_, wifes1_.id as id3_, wifes1_.id as id1_0_, wifes1_.name as name1_0_, wifes1_.husbandid as husbandid1_0_ from husband husband0_ left outer join wife wifes1_ on husband0_.id=wifes1_.husbandid where husband0_.id=?

즉시 불 러 오기 정책 을 사용 하 는 동시에 연결 캡 처 정책 을 사용 하면 sql 문 구 를 연결 하면 주 대상 과 관련 대상 을 찾 을 수 있 습 니 다.
  Scenario 4:lazy="false" fetch="select"
  
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_0_, husband0_.name as name0_0_ 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=?
 즉시 불 러 오기 정책 을 사용 하 는 동시에 select 캡 처 정책 을 사용 하면 두 개의 sql 문 구 를 보 냅 니 다. 첫 번 째 조 는 주 대상 을 조회 하 는 데 사용 되 고 두 번 째 조 는 관련 대상 을 조회 합 니 다.

좋은 웹페이지 즐겨찾기