Spring 다중 datasource 설정

다중 datasource 설정을 해보자

연결할 DB는 postgresql과 hive다


context-datasource.xml 설정

각 bean의 id를 다르게 해주어야 한다.

hive연결에서는 dbcp 연결하니깐 인증에러가 떠서 jdbc 연결로 바꿨다.

hive연결의 dependency 설정은 다음 링크 참고

JDBC-Hive 연결

<!-- postgresql -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
	<property name="driverClassName" value="org.postgresql.Driver" />
	<property name="url" value="jdbc:postgresql://localhost:5432/postgres" />
	<property name="username" value="postgres" />
	<property name="password" value="rootpass" />
</bean>

<!-- hive -->
<bean id="hiveDataSource" class="org.springframework.jdbc.datasource.SimpleDriverDataSource">
	<property name="driverClass" value="org.apache.hive.jdbc.HiveDriver" />
	<property name="url" value="jdbc:hive2://bdmn01.kcg.go.kr:10000/;auth=noSasl;user=hive" />
</bean>


context-transaction.xml 설정

각 bean의 id를 다르게 해주고, 각 property에 맞는 ref 설정

<!-- postgresql -->
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
	<property name="dataSource" ref="dataSource"/>
</bean>

<tx:advice id="txAdvice" transaction-manager="txManager">
	<tx:attributes>
		<tx:method name="*" rollback-for="Exception"/>
	</tx:attributes>
</tx:advice>


<!-- hive -->
<bean id="hiveTxManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
	<property name="dataSource" ref="hiveDataSource"/>
</bean>

<tx:advice id="hiveTxAdvice" transaction-manager="hiveTxManager">
	<tx:attributes>
		<tx:method name="*" rollback-for="Exception"/>
	</tx:attributes>
</tx:advice>


context-mapper.xml 설정

각 bean의 id, ref 다르게 해주고

두개 DB의 mapperLocations와 basePackage의 경로를 겹치지 않도록 해주어야 한다.

context-mapper

<!-- postgresql -->
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
	<property name="dataSource" ref="dataSource" />
	<property name="configLocation" value="classpath:/egovframework/sqlmap/sql-mapper-config.xml" />
	<property name="mapperLocations" value="classpath:/egovframework/sqlmap/mappers/*.xml" />
</bean>

<bean class="egovframework.rte.psl.dataaccess.mapper.MapperConfigurer">
	<property name="basePackage" value="kr.go.sb.portal.dev"/>
	<property name="sqlSessionFactoryBeanName" value="sqlSession" />
</bean>

<!-- hive -->
<bean id="hiveSqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
	<property name="dataSource" ref="hiveDataSource" />
	<property name="configLocation" value="classpath:/egovframework/sqlmap/sql-mapper-config.xml" />
	<property name="mapperLocations" value="classpath:/egovframework/sqlmap/hivemappers/*.xml" />
</bean>

<bean class="egovframework.rte.psl.dataaccess.mapper.MapperConfigurer">
	<property name="basePackage" value="kr.go.sb.portal.hive"/>
	<property name="sqlSessionFactoryBeanName" value="hiveSqlSession" />
</bean>


package 구성

package

hive의 mapper가 바라보는 hive 패키지에는 mapper.java와 사용하는 VO만 만들어주고

dev패키지의 service에서 hive의 mapper클래스를 선언해준다.

Leave a comment