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.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

@Configuration
@MapperScan(basePackages = "cn.hnthyy.thmz.mapper.thmz", sqlSessionTemplateRef  = "thmzSqlSessionTemplate")
public class ThmzDataSource {
    /**
     * 多数据源工程，这是导致这个配置没有生效的原因，因为他不知道为哪个数据源开启驼峰命名
     * 所以我们需要在配置多数据源的文件中，单独加入配置，（其他配置也是如此，只要涉及到多数据源的，都需要给每一个数据源去配置）
     * @return
     */
    @Bean(name = "thmzConfiguration")
    @ConfigurationProperties(prefix = "mybatis.configuration")
    public org.apache.ibatis.session.Configuration thmzConfiguration(){
        return new org.apache.ibatis.session.Configuration();
    }

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

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

    @Bean(name = "thmzTransactionManager")
    public DataSourceTransactionManager thmzTransactionManager(@Qualifier("thmzData") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "thmzSqlSessionTemplate")
    public SqlSessionTemplate thmzSqlSessionTemplate(@Qualifier("thmzSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

}