package com.reptileclient.jlifeapp.config.datasource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.jdbc.DataSourceBuilder;
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 tk.mybatis.spring.annotation.MapperScan;

import javax.sql.DataSource;

/**
 * @author fuxubing
 */
@Configuration
@MapperScan(basePackages = "com.reptileclient.jlifeapp.dao.hm", sqlSessionTemplateRef = "hmSqlSessionTemplate")
public class MybatisConfigHmOrder {
    @Autowired
    private DataSourceConfig dataSourceConfig;

    static final String MAPPER_LOCATION = "classpath:mybatis/mapper/hm/*.xml";

    /**
     * 创建数据源
     */
    @Bean(name = "hmDS")
    public DataSource gethmDataSource() {
        DataSource build = DataSourceBuilder.create()
                .driverClassName(dataSourceConfig.getDriverClassName())
                .url(dataSourceConfig.getDbUrl_hm())
                .username(dataSourceConfig.getUsername_hm())
                .password(dataSourceConfig.getPassword_hm())
                .build();
        return build;
    }


    /**
     * 创建SessionFactory
     */
    @Bean(name = "hmSqlSessionFactory")
    public SqlSessionFactory hmSqlSessionFactory(@Qualifier("hmDS") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        //设置mapper配置文件
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_LOCATION));
        bean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
        return bean.getObject();
    }

    /**
     * 创建事务管理器
     */
    @Bean("hmTransactionManger")
    public DataSourceTransactionManager hmTransactionManger(@Qualifier("hmDS") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    /**
     * 创建SqlSessionTemplate
     */
    @Bean(name = "hmSqlSessionTemplate")
    public SqlSessionTemplate hmSqlSessionTemplate(@Qualifier("hmSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
