额外:通俗易懂理清mybatis中SqlSession、SqlSessionTemplate、SessionFactory和SqlSessionFactoryBean之间的关系
配置文件
spring:
datasource:
# 数据源1
test1:
url: jdbc:mysql://localhost:3306/test1
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
# 数据源2
test2:
url: jdbc:mysql://localhost:3306/test2
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
数据源配置类
数据源1
@Configuration
// 配置Mapper扫描路径,以及会话工厂
@MapperScan(basePackages = {"cn.ydcat.dao.test1"}, sqlSessionFactoryRef = "test1SqlSessionFactory")
public class Test1DatasourceConfig {
// xml路径
private final static String MAPPER_PATH = "classpath:mapper/test1/*.xml";
/**
* 构建数据源
* @return
*/
@Bean
@ConfigurationProperties(prefix = "spring.datasource.test1") // 配置项前缀,根据实际修改
public DataSource test1DataSource(){
return DruidDataSourceBuilder.create().build();
}
/**
* 构建会话工厂
* @param test1DataSource
* @return
* @throws Exception
*/
@Bean
public SqlSessionFactory test1SqlSessionFactory(DataSource test1DataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(test1DataSource);
// 注意getResources,结尾有s
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_PATH));
return bean.getObject();
}
/**
* 构建会话
* @param test1SqlSessionFactory
* @return
*/
@Bean
public SqlSessionTemplate test1SqlSessionTemplete(SqlSessionFactory test1SqlSessionFactory){
return new SqlSessionTemplate(test1SqlSessionFactory);
}
/**
* 配置事务管理器
* @param test1DataSource
* @return
*/
@Bean
public DataSourceTransactionManager test1DataSourceTransactionManager(DataSource test1DataSource){
return new DataSourceTransactionManager(test1DataSource);
}
数据源2
基本和数据源1一致
需要详细检查各个bean名和xml路径,和其他数据源不一致
@Configuration
@MapperScan(basePackages = {"cn.ydcat.dao.test2"}, sqlSessionFactoryRef = "test2SqlSessionFactory")
public class Test2DatasourceConfig {
private final static String MAPPER_PATH = "classpath:mapper/test2/*.xml";
/**
* 构建数据源
* @return
*/
@Bean
@ConfigurationProperties(prefix = "spring.datasource.test2")
public DataSource test2DataSource(){
return DruidDataSourceBuilder.create().build();
}
/**
* 构建会话
* @param test2DataSource
* @return
* @throws Exception
*/
@Bean
public SqlSessionFactory test2SqlSessionFactory(DataSource test2DataSource) throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(test2DataSource);
bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources(MAPPER_PATH));
return bean.getObject();
}
@Bean
public SqlSessionTemplate test2SqlSessionTemplete(SqlSessionFactory test2SqlSessionFactory){
return new SqlSessionTemplate(test2SqlSessionFactory);
}
@Bean
public DataSourceTransactionManager test2DataSourceTransactionManager(DataSource test2DataSource){
return new DataSourceTransactionManager(test2DataSource);
}
}
Mapper
不详细阐述,与单数据源一致
注意Mapper路径,Mapper、xml路径需和对应数据源的配置文件中扫描的路径一致
使用
和单数据源一致,正常使用即可