package com.ygtx.gxt.conf;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * 源数据库数据源配置
 * 用于设备同步任务从其他数据库获取数据
 */
@Configuration
@MapperScan(
    basePackages = "com.ygtx.gxt.mapper.source",
    sqlSessionFactoryRef = "sourceSqlSessionFactory"
)
public class SourceDataSourceConfig {

    /**
     * 源数据库数据源
     * 
     * @return DataSource 数据源
     */
    @Bean(name = "sourceDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.druid.source")
    public DataSource sourceDataSource() {
        return new DruidDataSource();
    }

    @Bean
    public SqlSessionFactory sourceSqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(sourceDataSource());
        // 可以设置单独的mapper.xml路径
        sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver()
                .getResources("classpath:mapper/gxt/source/*.xml"));
        return sessionFactory.getObject();
    }
}