package com.dhcc.finance.config;

import java.sql.SQLException;

import javax.sql.DataSource;

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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import com.dhcc.finance.config.DBConfigOracle;

import oracle.jdbc.pool.OracleDataSource;
import oracle.jdbc.xa.client.OracleXADataSource;
/**
 * @ClassName: MyBatisConfigOracle 
 * @Description: TODO(oracle配置类)
 * @author lipeng 
 * @date 2019年10月12日 下午11:07:12
 * @see
 */

@Configuration
@MapperScan(basePackages = "com.dhcc.finance.main.dao.Oracle", sqlSessionTemplateRef = "OracleSqlSessionTemplate")
public class MyBatisConfigOracle {
    private static final String MAPPER_LOCATION = "classpath:mapper/oracle/*.xml";
	// 配置数据源

	@Bean(name = "oracleDataSource")
	public DataSource oracleDataSource(DBConfigOracle testConfig) throws SQLException {
		OracleDataSource oracleXADataSource = new OracleXADataSource();
		oracleXADataSource.setURL(testConfig.getUrl());
		oracleXADataSource.setPassword(testConfig.getPassword());
		oracleXADataSource.setUser(testConfig.getUsername());
		return oracleXADataSource;
	}

	@Bean(name = "oracleSqlSessionFactory")
	public SqlSessionFactory oracleSqlSessionFactory(@Qualifier("oracleDataSource") DataSource dataSource)
			throws Exception {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean(); // 创建session工厂
		bean.setDataSource(dataSource);// 设置数据源
		
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        bean.setMapperLocations(resolver.getResources(MyBatisConfigOracle.MAPPER_LOCATION)); // 指定mapper.xml文件位置

		return bean.getObject(); // 返回FactoryBean创建的Bean实例
	}
	

	@Bean(name = "OracleSqlSessionTemplate")
	public SqlSessionTemplate OracleSqlSessionTemplate(
			@Qualifier("oracleSqlSessionFactory") SqlSessionFactory oracleSqlSessionFactory) throws Exception {
		return new SqlSessionTemplate(oracleSqlSessionFactory);
	}
}
