package cn.hnthyy.thmz.common.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.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
@Configuration
@MapperScan(basePackages = "cn.hnthyy.thmz.mapper.his", sqlSessionTemplateRef  = "hisSqlSessionTemplate")
public class HisDataSource {
    /**
     * 多数据源工程，这是导致这个配置没有生效的原因，因为他不知道为哪个数据源开启驼峰命名
     * 所以我们需要在配置多数据源的文件中，单独加入配置，（其他配置也是如此，只要涉及到多数据源的，都需要给每一个数据源去配置）
     * @return
     */
    @Bean(name = "hisConfiguration")
    @ConfigurationProperties(prefix = "mybatis.configuration")
    @Primary
    public org.apache.ibatis.session.Configuration hisConfiguration(){
        return new org.apache.ibatis.session.Configuration();
    }


    @Bean(name = "hisData")
    @ConfigurationProperties(prefix = "spring.datasource.his") // application.yml
    @Primary
    public DataSource  hisData() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "hisSqlSessionFactory")
    @Primary
    public SqlSessionFactory hisSqlSessionFactory(@Qualifier("hisData") DataSource dataSource,@Qualifier("hisConfiguration") org.apache.ibatis.session.Configuration configuration) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setConfiguration(configuration);
        return bean.getObject();
    }

    @Bean(name = "hisTransactionManager")
    @Primary
    public DataSourceTransactionManager hisTransactionManager(@Qualifier("hisData") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "hisSqlSessionTemplate")
    @Primary
    public SqlSessionTemplate hisSqlSessionTemplate(@Qualifier("hisSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}