Spring Boot 시작하기
- #7. Mybatis Multi DataSource 운용
이번장에서는 Spring boot로 mybatis 연동시 2개 이상의 DataSource를 연동하는 방법을 살펴 보도록 하겠습니다. 앞장의 설정과 곂치는 부분이 있으니 참고부탁드려요.
pom.xml 에 아래 내용 추가.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.3</version>
</dependency>
# dependency 추가 후 이클립스에서 alt + F5를 실행하면 자동으로 jar파일들을 추가합니다. ( 프로젝트 우클릭 -> maven -> Update Project.. )
application.properties내에 아래 내용 추가
두개의 db계정에 대한 정보 설정
# DB1
spring.db1.datasource.driverClassName=org.mariadb.jdbc.Driver
spring.db1.datasource.url=jdbc:mariadb://localhost1:3306/test1
spring.db1.datasource.username=test
spring.db1.datasource.password=test
# DB2
spring.db2.datasource.driverClassName=org.mariadb.jdbc.Driver
spring.db2.datasource.url=jdbc:mariadb://localhost2:3306/test2
spring.db2.datasource.username=test
spring.db2.datasource.password=test
아래와 같이 DataBaseConfig 파일을 두개로 생성합니다.
Database1Config.java
package com.example;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@MapperScan(value="com.example.dao1", sqlSessionFactoryRef="db1SqlSessionFactory")
@EnableTransactionManagement
public class Db1DatabaseConfig {
@Bean(name = "db1DataSource")
@Primary
@ConfigurationProperties(prefix = "spring.db1.datasource")
public DataSource db1DataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "db1SqlSessionFactory")
@Primary
public SqlSessionFactory db1SqlSessionFactory(@Qualifier("db1DataSource") DataSource db1DataSource, ApplicationContext applicationContext) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(db1DataSource);
sqlSessionFactoryBean.setMapperLocations(applicationContext.getResources("classpath:com/example/dao1/*.xml"));
return sqlSessionFactoryBean.getObject();
}
@Bean(name = "db1SqlSessionTemplate")
@Primary
public SqlSessionTemplate db1SqlSessionTemplate(SqlSessionFactory db1SqlSessionFactory) throws Exception {
return new SqlSessionTemplate(db1SqlSessionFactory);
}
}
Database2Config.java
package com.example;
import javax.sql.DataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@MapperScan(value="com.example.dao2", sqlSessionFactoryRef="db2SqlSessionFactory")
@EnableTransactionManagement
public class Db2DatabaseConfig {
@Bean(name = "db2DataSource")
@ConfigurationProperties(prefix = "spring.db2.datasource")
public DataSource db2DataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "db2SqlSessionFactory")
public SqlSessionFactory db2SqlSessionFactory(@Qualifier("db2DataSource") DataSource db2DataSource, ApplicationContext applicationContext) throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(db2DataSource);
sqlSessionFactoryBean.setMapperLocations(applicationContext.getResources("classpath:com/example/dao2/*.xml"));
return sqlSessionFactoryBean.getObject();
}
@Bean(name = "db2SqlSessionTemplate")
public SqlSessionTemplate db2SqlSessionTemplate(SqlSessionFactory db2SqlSessionFactory) throws Exception {
return new SqlSessionTemplate(db2SqlSessionFactory);
}
}
DbController.java
package com.example.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.example.service.DbService;
@RestController
public class DbController {
@Autowired
DbService dbService;
@RequestMapping("/")
public @ResponseBody String root_test() throws Exception{
return "Hello World";
}
@RequestMapping("/db1")
public @ResponseBody String db1() throws Exception{
return dbService.getDb1Dual();
}
@RequestMapping("/db2")
public @ResponseBody String db2() throws Exception{
return dbService.getDb2Dual();
}
}
DbService.java
package com.example.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.example.dao1.Db1Mapper;
import com.example.dao2.Db2Mapper;
@Service
public class DbService {
@Autowired
Db1Mapper db1Mapper;
@Autowired
Db2Mapper db2Mapper;
/* select dual */
public String getDb1Dual() throws Exception{
return db1Mapper.getDb1Dual();
}
/* select dual */
public String getDb2Dual() throws Exception{
return db2Mapper.getDb2Dual();
}
}
Db1Mapper.java
package com.example.dao1;
public interface Db1Mapper {
public String getDb1Dual() throws Exception;
}
Db2Mapper.java
package com.example.dao2;
public interface Db2Mapper {
public String getDb2Dual() throws Exception;
}
Db1.xml
src/main/resources/com/exmaple/dao1/Db1.xml 로 생성
Db2.xml
src/main/resources/com/exmaple/dao2/Db2.xml 로 생성
여기 까지 진행하시면 두개의 Database로 연결되는 것을 보실 수 있으실껍니다.
해당 이클립스의 폴더 구조는 아래를 참고 하세요.
demo_muliDataSource.zip
위의 zip 파일을 풀어서 #5-2 이클립스 셋팅과 동일하게 진행하시면 바로 MultiDataSource 가 적용되는것을 확인하실 수 있으십니다.
솔라라스나 리눅스 같은 서버에도 그대로 풀어서 maven 만 실행하시면 동일한 웹프로젝트를 확인하실 수 있습니다.