JPA配置爲spring.datasource前綴,mybatis爲spring.datasource.eps開頭
1.創建DataSourceConfig配置類,來定義數據源 其實 @Primary表示默認,如果使用了JPA則默認使用該數據源
package com.xinyuan.core.config;
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.context.annotation.Primary;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import javax.sql.DataSource;
@Configuration
public class DataSourceConfig {
@Bean(name = "tenderDataSource")
@Qualifier("tenderDataSource")
@Primary
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource primaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "epsDataSource")
@Qualifier("epsDataSource")
@ConfigurationProperties(prefix = "spring.datasource.eps")
public DataSource secondaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "epsJdbcTemplate")
@Primary
@Qualifier("epsJdbcTemplate")
public NamedParameterJdbcTemplate primaryJdbcTemplate(
@Qualifier("epsDataSource") DataSource dataSource) {
return new NamedParameterJdbcTemplate(dataSource);
}
}
2.配置MyBatis
package com.xinyuan.core.config;
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.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import javax.sql.DataSource;
/**
* @author gaoyuzhe
* @date 2018/1/16.
*/
@Configuration
@MapperScan(basePackages = {"com.xinyuan.tender.mapper"}, sqlSessionFactoryRef = "sqlSessionFactory")
public class MyBatisConfig {
@Autowired
@Qualifier("epsDataSource")
private DataSource mybaitsDs;
@Bean
public SqlSessionFactory sqlSessionFactory() throws Exception {
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
// 使用epsDataSource數據源, 連接業務庫
factoryBean.setDataSource(mybaitsDs);
Resource[] mapperLocations = new PathMatchingResourcePatternResolver().getResources("classpath:mapper/*.xml");
factoryBean.setMapperLocations(mapperLocations);
return factoryBean.getObject();
}
@Bean
public SqlSessionTemplate sqlSessionTemplate() throws Exception {
// 使用上面配置的Factory
SqlSessionTemplate template = new SqlSessionTemplate(sqlSessionFactory());
return template;
}
}