목표 - springboot , gradle , mybatis 를 다중 db 클라이언트를 사용
[문제]
1. springboot , mybatis는 기본적으로 mapper 연동이 들어감. 기존 sqlsession 과 방식이 다름. 기존 소스때문에 mapper 연동하는것 말고 기존 mybatis 사용방식으로 사용해야함. 근데 springboot는 xml 방식이 아니라서 다름.
2. 아래 문서대로 따라하면 application.properties 에서 설정 못한다. 자바 소스로 설정해야함.
3. 다중으로 바꾸면서 소스로 바꿨더니 hikariCP 에러 나온다.
4. 설정파일이 안먹어서, alias를 xml로 안하고 어떻게 처리할지 몰랏음.
[해결]
1. 아래 복붙한 문서대로 일단 따라함.
그럼 동작은 가능하나 . alias 나 application.properties 에서 셋팅한 설정값이 안먹음.
2. application 의 설정값이 안먹어서, java 소스로 설정을 입력해주었음.
3. hikariCP 에러는 https://jojoldu.tistory.com/296 여기서 보고 해결함. 그냥 url 이름을 jdbc-url로 바꿈.
4. 2번과 동일하게 JAVA 소스로 설정함
https://blog.lanyonm.org/articles/2014/04/21/spring-4-mybatis-java-config.html
추가
- mapper 방식으로 application.properties를 사용가능하려면 기본셋팅인
spring.datasource.driver-class-name 이런식의 설정값을 써야함. 그러면 자동으로 mybatis를 db와 함께 인식하는 것으로 보임.
이러면 단일 DB만 가능하겟지..
공식문서
http://www.mybatis.org/spring/ko/sqlsession.html
http://www.mybatis.org/spring-boot-starter/mybatis-spring-boot-autoconfigure/
-----------------------------------------------------------------------------------------------------------------------------
스프링 부트에서 다중으로 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 |
이정도만 있으면 이후는 구성 하실 수 있을 것으로 보입니다.
https://sherwher.blogspot.com/2018/05/springboot-mybatis-database-setting.html
Using an SqlSession
'Web > SpringBoot' 카테고리의 다른 글
Access a File from the Classpath in a Spring Application (0) | 2019.04.10 |
---|---|
Spring Boot - Apache Kafka 카프카 연동 (0) | 2019.03.29 |
Spring @Qualifier isn't working without @Primary [duplicate] (0) | 2019.03.19 |
Read properties file outside JAR file (0) | 2019.03.15 |
Spring boot Actuator를 이용하여 스프링 애플리케이션 정보 모니터링 하기 (java application state/performance check) (0) | 2019.03.15 |
댓글