[SpringBoot] Mybatis 다중 Database Setting

스프링 부트에서 다중으로 Database셋팅하는 법입니다. Mybatis기준 Mapper를 따로 사용하지 않고 SqlSession을 사용하는 법입니다. 이틀간 고생했네요...

먼저 Config파일 입니다.

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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
//firstDatabase Setting
  
import javax.sql.DataSource;
 
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
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.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
 
@Configuration
@EnableTransactionManagement
public class DBConnectConfigFirst{
    
    @Bean(name="firstDataSource")
    @Primary
    @ConfigurationProperties(prefix="spring.first.datasource")
    public DataSource firstDataScource() {
        return DataSourceBuilder.create().build();
    }
    
    
    @Bean(name="firstSqlSessionFactory")
    @Primary
    public SqlSessionFactory firstSqlSessionFactory(@Qualifier("firstDataSource") DataSource dataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sessionFactory.setMapperLocations(resolver.getResources("classpath:mybatisMapper/first/Mapping-*.xml"));
        return sessionFactory.getObject();
    }
 
    @Bean(name = "firstSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate firstSqlSessionTemplate(@Qualifier("firstSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
      final SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory);
      return sqlSessionTemplate;
    }
    
    @Bean(name = "firstDataSourceTransactionManager")
    @Primary
    public DataSourceTransactionManager transactionManager (@Qualifier("firstDataSource") DataSource dataSource){
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource);
        return transactionManager;
    }
    
    
 
}
 
cs
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
46
47
48
49
50
51
52
53
54
//secondDatabase Setting
 

 
import javax.sql.DataSource;
 
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
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.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
 
@Configuration
@EnableTransactionManagement
public class DBConnectConfigSecond{
    
    @Bean(name="secondDataSource")
    @ConfigurationProperties(prefix="spring.second.datasource")
    public DataSource secondDataScource() {
        return DataSourceBuilder.create().build();
    }
    
    
    @Bean(name="secondSqlSessionFactory")
    public SqlSessionFactory secondSqlSessionFactory(@Qualifier("secondDataSource") DataSource dataSource) throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        sessionFactory.setMapperLocations(resolver.getResources("classpath:mybatisMapper/second/Mapping-*.xml"));
        return sessionFactory.getObject();
    }
 
    @Bean(name = "secondSqlSessionTemplate")
    public SqlSessionTemplate firstSqlSessionTemplate(@Qualifier("secondSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
      final SqlSessionTemplate sqlSessionTemplate = new SqlSessionTemplate(sqlSessionFactory);
      return sqlSessionTemplate;
    }
    
    @Bean(name = "secondDataSourceTransactionManager")
    public DataSourceTransactionManager transactionManager (@Qualifier("secondDataSource") DataSource dataSource){
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource);
        return transactionManager;
    }
    
    
 
}
cs

다음은 application.properties입니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#SERVER PORT
server.port=1983
 
 
#DB CONNECT INFO
spring.first.datasource.platform=oracle
spring.first.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.first.datasource.url=jdbc:oracle:thin:@(dburl):(port):(sid)
spring.first.datasource.username=(username)
spring.first.datasource.password=(userpassword)
 
 
#OTHER DB CONNECT INFO
spring.second.datasource.platform=mssql
spring.second.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.second.datasource.url=jdbc:sqlserver://(dburl):(port);DatabaseName=(DatabaseName);
spring.second.datasource.username=(username)
spring.second.datasource.password=(userpassword)
cs

다음은 sqlSessionTemplate를 쉽게 이용하기 위한 Abstract클래스 입니다. 

firstSqlSessionFactory를 주입하여 SqlSessionTemplate를 만듭니다. 아래로 다음과 같은 함수를 호출하여 편하게 사용하기 위하여 만들었습니다. firstSqlSessionFactory를 secordSqlSessionFactory로 바꾸어 똑같이 AbstractDAO파일을 하나 더 만듭니다.

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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import java.util.List;
 
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
 
 
public class AbstractDAO {
    
    private static final Logger logger = LoggerFactory.getLogger(AbstractDAO.class);
    
    @Autowired
    @Qualifier("firstSqlSessionTemplate")
    private SqlSessionTemplate sqlSession;
    
    protected void printQueryId(String queryId) {
            if(logger.isDebugEnabled()){
                logger.debug("\t QueryId  \t:  " + queryId);
            }
        }
    
 
    public int insert(String queryId, Object params){    
        printQueryId(queryId);    
        return sqlSession.insert(queryId, params);    
    } 
    
    public int update(String queryId, Object params){    
        printQueryId(queryId);    
        return sqlSession.update(queryId, params);    
    }
        
    public Object delete(String queryId, Object params){    
        printQueryId(queryId);    
        return sqlSession.delete(queryId, params);    
    }
    
    public Object selectOne(String queryId){    
        printQueryId(queryId);    
        return sqlSession.selectOne(queryId);    
    }
    
    public Object selectOne(String queryId, Object params){    
        printQueryId(queryId);    
        return sqlSession.selectOne(queryId, params);    
    }
    
    
    @SuppressWarnings("rawtypes")    
    public List selectList(String queryId){    
        printQueryId(queryId);    
        return sqlSession.selectList(queryId);    
    }
        
    @SuppressWarnings("rawtypes")    
    public List selectList(String queryId, Object params){    
        printQueryId(queryId);    
        return sqlSession.selectList(queryId,params);    
    }
 
}
 
cs
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import java.util.List;
 
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
 
public class OtherAbstractDAO {
    private static final Logger logger = LoggerFactory.getLogger(OtherAbstractDAO.class);
    @Autowired
    @Qualifier("secondSqlSessionTemplate")
    private SqlSessionTemplate sqlSession;
    protected void printQueryId(String queryId) {
        if(logger.isDebugEnabled()){
            logger.debug("\t QueryId  \t:  " + queryId);
        }
    }
    public int insert(String queryId, Object params){    
        printQueryId(queryId);    
        return sqlSession.insert(queryId, params);    
    } 
    
    public int update(String queryId, Object params){    
        printQueryId(queryId);    
        return sqlSession.update(queryId, params);    
    }
        
    public Object delete(String queryId, Object params){    
        printQueryId(queryId);    
        return sqlSession.delete(queryId, params);    
    }
    
    public Object selectOne(String queryId){    
        printQueryId(queryId);    
        return sqlSession.selectOne(queryId);    
    }
    
    public Object selectOne(String queryId, Object params){    
        printQueryId(queryId);    
        return sqlSession.selectOne(queryId, params);    
    }
    
    
    @SuppressWarnings("rawtypes")    
    public List selectList(String queryId){    
        printQueryId(queryId);    
        return sqlSession.selectList(queryId);    
    }
        
    @SuppressWarnings("rawtypes")    
    public List selectList(String queryId, Object params){    
        printQueryId(queryId);    
        return sqlSession.selectList(queryId,params);    
    }
    
    
}
 
cs

이정도만 있으면 이후는 구성 하실 수 있을 것으로 보입니다. 




댓글

이 블로그의 인기 게시물

[스위프트3] DateString을 기존 format에서 새로운 format으로 변경

[스위프트3] URLEncoding/Decoding