Spring 다 중 데이터 원본 트 랜 잭 션 솔 루 션
저 는 개발 환경: spring 4.2 + hibenate 4.2 + tomcat 7.0 을 사용 합 니 다.
질문
디자인 을 시작 할 때 두 개의 데이터 원본, 두 개의 Session Factory 와 두 개의 사무 HibernateTransactionManager 를 설정 하고 HibernateTemplate 를 이용 하여 데이터 베 이 스 를 조작 합 니 다.다음은 주요 설정:
applicationContext.xml
<?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:p="http://www.springframework.org/schema/p"
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.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd"
>
<import resource="applicationContext_framework.xml"/>
<import resource="applicationContext_stk.xml"/>
</beans>
서로 다른 데이터 베 이 스 를 위 한 두 개의 설정 가 져 오기applicationContext_framework.xml
<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd"
>
<context:component-scan base-package="com.framework.dao"/>
<context:component-scan base-package="com.framework.dao.mssql"/>
<context:component-scan base-package="com.framework.service"/>
<context:component-scan base-package="com.framework.action"/>
<bean id="propertyConfigurerFW"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:framework.properties"/>
</bean>
<bean id="datasourceFW"
class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close"
p:driverClassName="${jdbc.driverClassName}"
p:url="${jdbc.url}"
p:username="${jdbc.username}"
p:password="${jdbc.password}" />
<bean id="sessionFactoryFW"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="datasourceFW"/>
<!-- -->
<property name="packagesToScan" value="com.framework.domain"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">com.util.SQLServerDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<!-- 4.0-->
<prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>
<prop key="hibernate.cache.use_second_level_cache">true</prop>
</props>
</property>
</bean>
<bean id="hibernateTemplateFW"
class="org.springframework.orm.hibernate4.HibernateTemplate"
p:sessionFactory-ref="sessionFactoryFW" />
<bean id="transactionManagerFW"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactoryFW" />
</bean>
<tx:advice id="txAdvice" transaction-manager="transactionManagerFW">
<tx:attributes>
<tx:method name="select*" read-only="true" propagation="REQUIRED"/>
<tx:method name="get*" read-only="true" propagation="REQUIRED"/>
<tx:method name="load*" read-only="true" propagation="REQUIRED"/>
<tx:method name="find*" read-only="true" propagation="REQUIRED"/>
<tx:method name="query*" read-only="true" propagation="REQUIRED"/>
<tx:method name="read*" read-only="true" propagation="REQUIRED"/>
<tx:method name="sync*"/>
<tx:method name="*" propagation="REQUIRED" rollback-for="Exception"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="pointcut" expression="execution(* com.framework.service.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
</aop:config>
</beans>
applicationContext_stk.xml <?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd"
>
<context:component-scan base-package="com.stk.dao.mssql"/>
<context:component-scan base-package="com.stk.service"/>
<context:component-scan base-package="com.stk.action"/>
<bean id="datasourceStk"
class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close"
p:driverClassName="${jdbcstk.driverClassName}"
p:url="${jdbcstk.url}"
p:username="${jdbcstk.username}"
p:password="${jdbcstk.password}" />
<bean id="sessionFactoryStk"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="datasourceStk"/>
<!-- -->
<property name="packagesToScan" value="com.stk.domain"/>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">com.util.SQLServerDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.">true</prop>
<!-- 4.0-->
<prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>
<prop key="hibernate.cache.use_second_level_cache">true</prop>
</props>
</property>
</bean>
<bean id="hibernateTemplateStk"
class="org.springframework.orm.hibernate4.HibernateTemplate"
p:sessionFactory-ref="sessionFactoryStk" />
<bean id="transactionManagerStk"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactoryStk" />
</bean>
<tx:advice id="txAdvice" transaction-manager="transactionManagerStk">
<tx:attributes>
<tx:method name="select*" read-only="true"/>
<tx:method name="get*" read-only="true"/>
<tx:method name="load*" read-only="true"/>
<tx:method name="find*" read-only="true"/>
<tx:method name="query*" read-only="true"/>
<tx:method name="read*" read-only="true"/>
<tx:method name="*" propagation="REQUIRED" rollback-for="Exception"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="pointcut" expression="execution(* com.stk.service.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut"/>
</aop:config>
</beans>
디자인 도 메 인 층, 서비스 층, Dao 층Dao 층 의 디자인 에 대해 저 는 BasoDao abstract 류 를 디자인 하여 모든 Dao 가 계승 할 수 있 도록 했 습 니 다.여러 데이터 베 이 스 를 조작 해 야 하기 때문에 BasoDao 클래스 에 abstract 함 수 를 추가 하여 hibenatetemplate. getSession 함 수 를 가 져 왔 습 니 다. 먼저 getCurrentSession () 을 통 해 가 져 왔 습 니 다. 실패 하면 openSession 을 통 해 가 져 옵 니 다.
기본 구 조 는 다음 과 같다.
package com.framework.dao;
/**
* DAO , DAO DAO, , 。
*/
public abstract class BaseDao<T> {
private Class<T> entityClass;
public abstract HibernateTemplate getHibernateTemplate();
/**
*
*/
public BaseDao() {
Type genType = getClass().getGenericSuperclass();
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
entityClass = (Class) params[0];
}
/**
* ID PO
*
* @param id
* @return PO
*/
public T load(Serializable id) {
return (T) getHibernateTemplate().load(entityClass, id);
}
/**
* ID PO
*
* @param id
* @return PO
*/
public T get(Serializable id) {
return (T) getHibernateTemplate().get(entityClass, id);
}
/**
* PO
*
* @return
*/
public List<T> loadAll() {
return getHibernateTemplate().loadAll(entityClass);
}
/**
* PO
*
* @param entity
*/
public void save(T entity) {
getHibernateTemplate().save(entity);
}
public void saveOrUpdate(T entity){
getHibernateTemplate().saveOrUpdate(entity);
}
/**
* PO
*
* @param entity
*/
public void remove(T entity) {
getHibernateTemplate().delete(entity);
}
/**
* PO
*
* @param entity
*/
public void update(T entity) {
getHibernateTemplate().update(entity);
}
public Session getSession() {
Session session = getHibernateTemplate().getSessionFactory().getCurrentSession();
if (session == null)
session = getHibernateTemplate().getSessionFactory().openSession();
return session;
}
}
두 가지 데 이 터 를 대상 으로 두 개의 Dao 류 를 설계 하여 BaseDao 에 계승 합 니 다.프레임 DAO, Framework Dao, spring 을 통 해 hibenateTemplate FW 를 자동 으로 주입 합 니 다.
public class FrameworkDao<T> extends BaseDao<T> {
@Autowired
private HibernateTemplate hibernateTemplateFW;
@Override
public HibernateTemplate getHibernateTemplate() {
return hibernateTemplateFW;
}
}
창고 DAO, StkDao, spring 을 통 해 hibenateTemplateStk 자동 주입public class StkDao<T> extends BaseDao<T> {
@Autowired
private HibernateTemplate hibernateTemplateStk;
@Override
public HibernateTemplate getHibernateTemplate() {
return hibernateTemplateStk;
}
}
테스트 를 통 해 이 설정 은 다음 과 같은 상황 이 발생 합 니 다.
1. 프레임 워 크 의 트 랜 잭 션 설정 이 작 동 하지 않 습 니 다. 조 회 는 문제 가 없 지만 삭제 에 성공 하지 못 했 습 니 다.
프레임 워 크 의 dao 방법 을 호출 할 때 다음 과 같은 오류 가 발생 합 니 다.
Could not retrieve pre-bound Hibernate session
Could not obtain transaction-synchronized Session for current thread
hibenatetemplate 의 실행 코드 를 분 석 했 습 니 다:
try {
session = this.getSessionFactory().getCurrentSession();
} catch (HibernateException var12) {
this.logger.debug("Could not retrieve pre-bound Hibernate session", var12);
}
if(session == null) {
session = this.getSessionFactory().openSession();
session.setFlushMode(FlushMode.MANUAL);
isNew = true;
}
getCurrentSession () 은 null, session. setFlushMode (FlushMode. MANUAL) 를 되 돌려 줍 니 다. 삭제 수정 은 COMMIT 가 필요 하지만 MANUAL 은 COMMIT 보다 작 습 니 다. protected void checkWriteOperationAllowed(Session session) throws InvalidDataAccessApiUsageException {
if(this.isCheckWriteOperations() && session.getFlushMode().lessThan(FlushMode.COMMIT)) {
throw new InvalidDataAccessApiUsageException("Write operations are not allowed in read-only mode (FlushMode.MANUAL): Turn your Session into FlushMode.COMMIT/AUTO or remove \'readOnly\' marker from transaction definition.");
}
}
2. stk 사 무 는 모든 것 이 정상 입 니 다.
이런 문제 가 발생 한 후에 나 는 다음 과 같은 설정 을 설명 했다.
<import resource="applicationContext_stk.xml"/>
프레임 워 크 의 트 랜 잭 션 설정 에 도움 이 되 었 으 니 삭제 와 수정 에 도 문제 가 없습니다.
결론: spring 의 jdbc 사무 (hibenate)
트 랜 잭 션) 하나의 트 랜 잭 션 설정 만 지원 합 니 다.
2. 해결 방법:
1. hibenatetemplate 을 사용 하지 말고 Session Factory 를 사용 하 세 요.
2. atomikos 프레임 워 크 사용
3. jta 사 무 를 사용 하지만 tomcat 는 지원 하지 않 습 니 다. jboss, weblogic 등 jta 를 지원 하 는 서버 만 사용 할 수 있 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.