package com.Config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import com.alibaba.druid.pool.DruidDataSource;

@Configuration
public class AppConfig1 {

  @Bean
  public DruidDataSource dataSource() {
    DruidDataSource ds = new DruidDataSource();
    ds.setDriverClassName("com.mysql.cj.jdbc.Driver");
    ds.setUrl("jdbc:mysql://localhost:3306/a_test?characterEncoding=utf8&useSSL=true&serverTimezone=Asia/Shanghai");
    ds.setUsername("root");
    ds.setPassword("root");
    ds.setInitialSize(5);
    return ds;
  }

  @Bean
  public DataSourceTransactionManager dataSourceTransactionManager() {
    return new DataSourceTransactionManager(dataSource());
  }

  @Bean
  public SqlSessionFactory sqlSessionFactory() throws Exception {
    SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
    sessionFactory.setDataSource(dataSource());
    sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
        .getResources("classpath:bean/UserMapper.xml"));
    sessionFactory.setTypeAliasesPackage("com/Domain"); // 扫包
    // 配置路径
    sessionFactory.setConfigLocation(new ClassPathResource("sqlMapConfig.xml"));

    return sessionFactory.getObject();
  }
  @Bean
  public MapperScannerConfigurer mapperScannerConfigurer() {
    MapperScannerConfigurer mScannerConfigurer = new MapperScannerConfigurer();

    mScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactory");
    mScannerConfigurer.setBasePackage("com/Mapper"); // 扫mapper
    return mScannerConfigurer;
  }

}