package kr.co.i4way.config;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSession;
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.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
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.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@Configuration
@MapperScan(value = "kr.co.i4way.mapper.mssql", sqlSessionFactoryRef = "mssqlSqlSessionFactory")
@EnableTransactionManagement
public class MssqlDataBaseConfig {
	 
	@Primary
    @Bean(name = "mssqlDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.mssql")
    public DataSource mssqlDataSource() { 
        return DataSourceBuilder.create().build();
    } 
	    
	@Primary
    @Bean(name = "mssqlSqlSessionFactory")
    public SqlSessionFactory mssqlSqlSessionFactory(@Autowired @Qualifier("mssqlDataSource") DataSource mssqlDataSource) throws Exception {
        SqlSessionFactoryBean sqlSessionFactory = new SqlSessionFactoryBean();
        sqlSessionFactory.setDataSource(mssqlDataSource);
        sqlSessionFactory.setConfigLocation(new PathMatchingResourcePatternResolver().getResource("classpath:mybatis-config.xml"));
        sqlSessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:kr/co/i4way/mybatis/mssql/*.xml"));
        return sqlSessionFactory.getObject();
    } 
	     
	@Primary
    @Bean(name = "mssqlSqlSession")
    public SqlSession sqlSession(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}	

