package net.vtstar.zhongtong.avi.global.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.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

@Configuration
@MapperScan(
        basePackages = {
                "net.vtstar.user.mapper",
                "net.vtstar.scada.base.equipmgt.mapper",
                "net.vtstar.zhongtong.avi.equipment.mapper",
                "net.vtstar.zhongtong.avi.sqlserver.mapper",
                "net.vtstar.zhongtong.avi.access.mapper",
                "net.vtstar.zhongtong.avi.laboratory.mapper",
                "net.vtstar.zhongtong.avi.gateway.parts.mapper"
        },
        sqlSessionFactoryRef = "sqlSessionFactoryMySQL")
public class MybatisMySQLConfig {

    @Autowired
    @Qualifier("dataSource")
    private DataSource dataSource;

    @Bean(name = "jdbcTemplate")
    @Primary
    public JdbcTemplate mySqlJdbcTemplate(
            @Qualifier("dataSource") DataSource dataSource) {
        return new JdbcTemplate(dataSource);
    }

    @Bean
    public SqlSessionFactory sqlSessionFactoryMySQL() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource);
        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mapper/mysql/*.xml"));
        return factoryBean.getObject();
    }

    @Bean
    public SqlSessionTemplate sqlSessionTemplate2() throws Exception {
        SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactoryMySQL()); // 使用上面配置的Factory
        return template;
    }
}
