Spring + Hibernate 동적 Session Factory 전환 실현 (개선 판)

12577 단어 springHibernate
앞 에 동적 전환 Hibernate Session Factory 에 관 한 글 이 쓰 여 있 습 니 다.
문제점 발견: 여러 개의 HibernateTransactionManager 와 여러 개의 Spring 절단면 을 설정 해 야 합 니 다. 이렇게 해서 두 가지 문 제 를 가 져 옵 니 다. 1. 프로그램의 효율 이 떨 어 집 니 다. Spring 이 여러 번 Advice 를 차단 하기 때 문 입 니 다. 2. 그 중 하나 인 Session Factory 연결 에 문제 가 생기 면,전체 시스템 이 작 동 하지 못 할 수 있 습 니 다. 오늘 은 이러한 문 제 를 해결 하 는 새로운 방법 을 연구 해 냈 습 니 다. 1. 데이터 원본 과 Hibernate Session Factory 설정:
 
<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:p="http://www.springframework.org/schema/p"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"  
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"  
    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-3.0.xsd  
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd  
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
    <!-- FOR SqlServer-->  
    <bean id="SqlServer_DataSource"  
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
        <property name="driverClassName" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />  
        <property name="url"  
            value="url" />  
        <property name="username" value="username" />  
        <property name="password" value="password" />  
    </bean>  
    <bean id="SqlServer_SessionFactory"  
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"  
        p:mappingLocations="classpath:/com/entity/*.hbm.xml">  
        <property name="dataSource" ref="SqlServer_DataSource" />       
        <property name="hibernateProperties">  
            <props>                 
                <prop key="hibernate.query.factory_class">org.hibernate.hql.ast.ASTQueryTranslatorFactory</prop>  
                <prop key="hibernate.dialect">org.hibernate.dialect.SQLServer2008Dialect</prop>               
                <prop key="hibernate.show_sql">true</prop>  
                <prop key="hibernate.format_sql">true</prop>  
            </props>  
        </property>  
    </bean>  
   
      
    <!-- FOR Oracle -->  
    <bean id="Oracle _DataSource"  
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">       
        <property name="driverClassName" value="oracle.jdbc.OracleDriver" />  
        <property name="url" value="jdbc:oracle:thin:@localhost:1521/orcl" />  
        <property name="username" value="username" />  
        <property name="password" value="password" />  
    </bean>  
    <bean id="Oracle_SessionFactory"  
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean"   
        p:mappingLocations="classpath:/com/entity/*.hbm.xml">  
        <property name="dataSource" ref="Oracle_DataSource" />          
        <property name="hibernateProperties">  
            <props>  
                <prop key="hibernate.query.factory_class">org.hibernate.hql.ast.ASTQueryTranslatorFactory</prop>  
                <prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>               
                <prop key="hibernate.show_sql">true</prop>  
                <prop key="hibernate.format_sql">true</prop>  
            </props>  
        </property>  
    </bean>  
  
      
      
</beans>  

 
2. 확장 인터페이스 DynamicSessionFactory Inf 계승 SessionFactory 정의
 
 
import org.hibernate.SessionFactory;

public interface DynamicSessionFactoryInf extends SessionFactory {

	public SessionFactory getHibernateSessionFactory();
}

 
3. DynamicSessionFactory 를 정의 하여 DynamicSessionFactory Inf 실현
 
public class DynamicSessionFactory implements DynamicSessionFactoryInf ,ApplicationContextAware{
	
	private static final long serialVersionUID = 1L;

	private ApplicationContext applicationContext;
	//    SessionFactory
	private SessionFactory getHibernateSessionFactory(String name) {
		return (SessionFactory) applicationContext.getBean(name);
	}
        //  DynamicSessionFactoryInf      
	public SessionFactory getHibernateSessionFactory() {
		return getHibernateSessionFactory(ThreadLocalUtil.getCurrentITAsset()
				.getSessionFactoryName());
	}
	
       //     SessionFactory     ,     SessionFactory      
	public Reference getReference() throws NamingException {
		return getHibernateSessionFactory().getReference();
	}

	

	public Session openSession() throws HibernateException {
		return getHibernateSessionFactory().openSession();
	}

	public Session openSession(Interceptor interceptor)
			throws HibernateException {
		return getHibernateSessionFactory().openSession(interceptor);
	}

	public Session openSession(Connection connection) {
		return getHibernateSessionFactory().openSession(connection);
	}

	public Session openSession(Connection connection, Interceptor interceptor) {
		return getHibernateSessionFactory().openSession(connection,interceptor);
	}

	public Session getCurrentSession() throws HibernateException {
		return getHibernateSessionFactory().getCurrentSession();
	}

	public StatelessSession openStatelessSession() {
		return getHibernateSessionFactory().openStatelessSession();
	}

	public StatelessSession openStatelessSession(Connection connection) {
		return getHibernateSessionFactory().openStatelessSession(connection);
	}

	public ClassMetadata getClassMetadata(Class entityClass) {
		return getHibernateSessionFactory().getClassMetadata(entityClass);
	}

	public ClassMetadata getClassMetadata(String entityName) {
		return getHibernateSessionFactory().getClassMetadata(entityName);
	}

	public CollectionMetadata getCollectionMetadata(String roleName) {
		return getHibernateSessionFactory().getCollectionMetadata(roleName);
	}

	public Map getAllClassMetadata() {
		return getHibernateSessionFactory().getAllClassMetadata();
	}

	public Map getAllCollectionMetadata() {
		return getHibernateSessionFactory().getAllCollectionMetadata();
	}

	public Statistics getStatistics() {
		return getHibernateSessionFactory().getStatistics();
	}

	public void close() throws HibernateException {
		getHibernateSessionFactory().close();
	}

	public boolean isClosed() {
		return getHibernateSessionFactory().isClosed();
	}

	public Cache getCache() {
		return getHibernateSessionFactory().getCache();
	}

	public void evict(Class persistentClass) throws HibernateException {
		getHibernateSessionFactory().evict(persistentClass);
	}

	public void evict(Class persistentClass, Serializable id)
			throws HibernateException {
		getHibernateSessionFactory().evict(persistentClass, id);
	}

	public void evictEntity(String entityName) throws HibernateException {
		getHibernateSessionFactory().evictEntity(entityName);
	}

	public void evictEntity(String entityName, Serializable id)
			throws HibernateException {
		getHibernateSessionFactory().evictEntity(entityName, id);
	}

	public void evictCollection(String roleName) throws HibernateException {
		getHibernateSessionFactory().evictCollection(roleName);
	}

	public void evictCollection(String roleName, Serializable id)
			throws HibernateException {
		getHibernateSessionFactory().evictCollection(roleName, id);
	}

	public void evictQueries(String cacheRegion) throws HibernateException {
		getHibernateSessionFactory().evictQueries(cacheRegion);
	}

	public void evictQueries() throws HibernateException {
		getHibernateSessionFactory().evictQueries();
	}

	public Set getDefinedFilterNames() {
		return getHibernateSessionFactory().getDefinedFilterNames();
	}

	public FilterDefinition getFilterDefinition(String filterName)
			throws HibernateException {
		return getHibernateSessionFactory().getFilterDefinition(filterName);
	}

	public boolean containsFetchProfileDefinition(String name) {
		return getHibernateSessionFactory().containsFetchProfileDefinition(name);
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.applicationContext = applicationContext;
	}

	

}

 
4. 동적 SessionFactory 설정
 
<bean id="sessionFactory" class="com.hp.it.qdpadmin.common.DynamicSessionFactory"/> 
 
 
5. DynamicTransactionManager 계승 HibernateTransactionManager 정의
 
public class DynamicTransactionManager extends HibernateTransactionManager {

	private static final long serialVersionUID = 1047039346475978451L;
	//  getDataSource  ,      
	public DataSource getDataSource() {
		DataSource sfds = SessionFactoryUtils.getDataSource(getSessionFactory());
		return sfds;
	}
       //  getSessionFactory  ,      SessionFactory
	public SessionFactory getSessionFactory() {
		DynamicSessionFactoryInf dynamicSessionFactory = (DynamicSessionFactoryInf) super
				.getSessionFactory();
		SessionFactory hibernateSessionFactory = dynamicSessionFactory
				.getHibernateSessionFactory();
		return hibernateSessionFactory;
	}
	//  afterPropertiesSet,            
	public void afterPropertiesSet() {
		return;
	}

}

 
6. dynamicTransactionManager 설정
 
<bean id="dynamicTransactionManager"
		class="com.hp.it.qdpadmin.common.DynamicTransactionManager">
		<property name="sessionFactory" ref="sessionFactory"/>
	</bean>
 
 
7. Session Factory 를 위 한 트 랜 잭 션 절단면 설정
 
<tx:advice id="dynamicTxAdvice" transaction-manager="dynamicTransactionManager">  
        <tx:attributes>  
            <tx:method name="get*" read-only="true" />  
            <tx:method name="find*" read-only="true" />  
            <tx:method name="*" propagation="REQUIRED" rollback-for="Exception" />  
        </tx:attributes>  
    </tx:advice>  
      
      
    <aop:config proxy-target-class="true">    
        <aop:pointcut id="txPointcut" expression="execution(* com.service.*.*(..))"/>          
        <aop:advisor advice-ref="dynamicTxAdvice" pointcut-ref="txPointcut" /> 
    </aop:config>  

좋은 웹페이지 즐겨찾기