package com.artifact.api.config;
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.boot.autoconfigure.jdbc.DataSourceBuilder;
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 org.springframework.core.io.support.ResourcePatternResolver;
/**
* 多数据源配置
* @description OtherDataSourceConfig.java
* @author LI
* @date 2018年10月26日 下午3:00:10
*/
@Configuration
@MapperScan(basePackages = {"com.artifact.api.othermapper"}, sqlSessionTemplateRef = "otherSqlSessionTemplate")
public class OtherDataSourceConfig {
@Bean(name = "otherDB")
@ConfigurationProperties(prefix = "spring.datasource.db2") // application.properteis中对应属性的前缀
public DataSource dataSource1() {
return DataSourceBuilder.create().build();
}
@Bean
public SqlSessionFactory otherSqlSessionFactory(@Qualifier("otherDB") DataSource dataSource)throws Exception{
SqlSessionFactoryBean bean= new SqlSessionFactoryBean();
bean.setDataSource(dataSource);
//添加XML目录
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
try{
bean.setMapperLocations(resolver.getResources("classpath*:com/artifact/api/othermapper/xml/*.xml"));
//在配置中加上这句代码 多数据源转驼峰就OK了
bean.getObject().getConfiguration().setMapUnderscoreToCamelCase(true);
return bean.getObject();
}catch(Exception e){
e.printStackTrace();
throw new RuntimeException(e);
}
}
@Bean
public SqlSessionTemplate otherSqlSessionTemplate(@Qualifier("otherSqlSessionFactory") SqlSessionFactory sqlSessionFactory ) throws Exception {
// 使用上面配置的Factory
SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory);
return template;
}
}