package com.sunxung.factoring.component.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.mybatis.spring.boot.autoconfigure.SpringBootVFS;
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.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/****
 * @className:SlaverDataSourceConfiguration
 * @description:从数据库配置
 * @author:杜小姣
 * @e-mail:1261237207@qq.com
 * @date:2018年12月7日 下午2:08:45
 */
@Configuration
@MapperScan(basePackages = "com.sunxung.factoring.inkassomapper", sqlSessionTemplateRef = "inkassoSqlSessionTemplate")
public class InkassoDataSourceConfiguration {

    @Bean(name = "inkassoDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.inkassoData")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }

    @Bean(name = "inkassoSqlSessionFactory")
    public SqlSessionFactory sqlSessionFactory(@Qualifier("inkassoDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setConfiguration(config());
        bean.setTypeAliasesPackage("com.sunxung.factoring.entity");
        bean.setVfs(SpringBootVFS.class);
        bean.setMapperLocations(
                new PathMatchingResourcePatternResolver().getResources("classpath*:/inkassomapper/**/*Mapper.xml"));
        return bean.getObject();
    }

    private org.apache.ibatis.session.Configuration config() {
        org.apache.ibatis.session.Configuration config = new org.apache.ibatis.session.Configuration();
        config.setMapUnderscoreToCamelCase(true);
        config.setUseGeneratedKeys(true);
        config.setDefaultFetchSize(100);
        config.setDefaultStatementTimeout(60);
        return config;
    }

    @Bean(name = "inkassoTransactionManager")
    public DataSourceTransactionManager transactionManager(@Qualifier("inkassoDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "inkassoSqlSessionTemplate")
    public SqlSessionTemplate sqlSessionTemplate(
            @Qualifier("inkassoSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
