Spring Boot 시작하기

- #7. Mybatis Multi DataSource 운용


이번장에서는 Spring boot로 mybatis 연동시 2개 이상의 DataSource를 연동하는 방법을 살펴 보도록 하겠습니다. 앞장의 설정과 곂치는 부분이 있으니 참고부탁드려요.



pom.xml 에 아래 내용 추가. 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<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계정에 대한  정보 설정

1
2
3
4
5
6
7
8
9
10
11
# 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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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

1
2
3
4
5
package com.example.dao1;
 
public interface Db1Mapper {
        public String getDb1Dual() throws Exception;
}


Db2Mapper.java

1
2
3
4
5
package com.example.dao2;
 
public interface Db2Mapper {
    public String getDb2Dual() throws Exception;
}


Db1.xml

src/main/resources/com/exmaple/dao1/Db1.xml 로 생성

1
2
3
4
5
6
7
8
9
<!--?xml version="1.0" encoding="UTF-8"?-->
 
<mapper namespace="com.example.dao1.Db1Mapper">
 
    <select id="getDb1Dual" resulttype="java.lang.String">
        SELECT 'DB1' FROM DUAL
    </select>
 
</mapper>



Db2.xml

src/main/resources/com/exmaple/dao2/Db2.xml 로 생성

1
2
3
4
5
6
7
8
9
<!--?xml version="1.0" encoding="UTF-8"?-->
 
<mapper namespace="com.example.dao2.Db2Mapper">
 
    <select id="getDb2Dual" resulttype="java.lang.String">
        SELECT 'DB2' FROM DUAL
    </select>
 
</mapper>



여기 까지 진행하시면 두개의 Database로 연결되는 것을 보실 수 있으실껍니다.


해당 이클립스의 폴더 구조는 아래를 참고 하세요.




demo_muliDataSource.zip


위의 zip 파일을 풀어서 #5-2 이클립스 셋팅과 동일하게 진행하시면 바로 MultiDataSource 가 적용되는것을 확인하실 수 있으십니다.


솔라라스나 리눅스 같은 서버에도 그대로 풀어서 maven 만 실행하시면 동일한 웹프로젝트를 확인하실 수 있습니다.



출처: http://jsijsi99.tistory.com/9?category=710810 [삽질대마왕 이대장]

 

+ Recent posts