package cn.reghao.tnb.file.app.config.mybatis;

import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
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 org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

/**
 * MyBatis 初始化配置
 * 若配置了多数据源，则不启用此配置
 *
 * @author reghao
 * @date 2021-04-26 17:48:29
 */
@Configuration
public class DataSourceConfig {
    private final DataSource dataSource;

    public DataSourceConfig(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setPlugins(new Interceptor[]{pageListInterceptor()});

        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true);
        configuration.setDefaultFetchSize(100);
        configuration.setDefaultStatementTimeout(600);
        factoryBean.setConfiguration(configuration);

        String location = "classpath*:mapper/**/**.xml";
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(location));
        return factoryBean.getObject();
    }

    /**
     * 配置 mybatis 的分页拦截器
     *
     * @param
     * @return
     * @date 2021-12-21 下午5:23
     */
    @Bean
    public PageListInterceptor pageListInterceptor() {
        return new PageListInterceptor();
    }

    @Bean(value = "sqlSession")
    public SqlSessionTemplate sqlSessionTemplate(SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }

    @Bean(value = "transactionManager")
    public PlatformTransactionManager annotationDrivenTransactionManager() {
        return new DataSourceTransactionManager(dataSource);
    }
}
