package com.miyzh.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
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.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * description: DruidConfig
 * date: 2020/6/19 10:29
 * author: SZQ
 */
@Configuration
@MapperScan(basePackages = "com.miyzh.mapper.prod", sqlSessionFactoryRef = "prodSqlSessionFactory")
public class ProdDataSourceConfig {

    @Bean("prodDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.prod")
    public DataSource getProdDataSource(){
        return DruidDataSourceBuilder.create().build();
    }

    @Bean("prodSqlSessionFactory")
    public SqlSessionFactory prodSqlSessionFactory(@Qualifier("prodDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        // mapper的xml形式文件位置必须要配置，不然将报错：no statement （这种错误也可能是mapper的xml中，namespace与项目的路径不一致导致）
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapping/prod/*.xml"));
        return bean.getObject();
    }

    @Bean("prodSqlSessionTemplate")
    public SqlSessionTemplate prodSqlSessionTemplate(@Qualifier("prodSqlSessionFactory") SqlSessionFactory sqlSessionFactory){
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}