spring+mybatis配置多数据源
背景:在springboot配置多数据源(一)的基础上进行
一、配置固定数据源
1. application.yml文件增加数据源
spring:
second-datasource:
username: root
password: 1234
jdbc-url: jdbc:mysql://127.0.0.1:3306/test2?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.zaxxer.hikari.HikariDataSource
hikari:
maximum-pool-size: 20
max-lifetime: 1800000
idle-timeout: 30000
data-source-properties:
prepStmtCacheSize: 250
prepStmtCacheSqlLimit: 2048
cachePrepStmts: true
useServerPrepStmts: true
third-datasource:
username: root
password: 1234
jdbc-url: jdbc:mysql://127.0.0.1:3306/test3?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.zaxxer.hikari.HikariDataSource
hikari:
maximum-pool-size: 20
max-lifetime: 1800000
idle-timeout: 30000
data-source-properties:
prepStmtCacheSize: 250
prepStmtCacheSqlLimit: 2048
cachePrepStmts: true
useServerPrepStmts: true
fourth-datasource:
username: root
password: 1234
jdbc-url: jdbc:mysql://127.0.0.1:3306/test4?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.zaxxer.hikari.HikariDataSource
hikari:
maximum-pool-size: 20
max-lifetime: 1800000
idle-timeout: 30000
data-source-properties:
prepStmtCacheSize: 250
prepStmtCacheSqlLimit: 2048
cachePrepStmts: true
useServerPrepStmts: true
2. 添加数据库配置(DataBaseConfig.java)
@Bean(name = "secondDataSource")
@ConfigurationProperties(prefix = "spring.second-datasource")
public DataSource secondDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "thirdDataSource")
@ConfigurationProperties(prefix = "spring.third-datasource")
public DataSource thirdDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "fourthDataSource")
@ConfigurationProperties(prefix = "spring.fourth-datasource")
public DataSource fourthDataSource() {
return DataSourceBuilder.create().build();
}
3. 分别进行各数据源配置
package com.zsx.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.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
@Configuration
@MapperScan(basePackages = {"com.zsx.mapper.primary"}, sqlSessionFactoryRef = "primarySqlSessionFactory")
public class MybatisDBPrimaryConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(MybatisDBPrimaryConfig.class);
@Bean(name = "primarySqlSessionFactory")
public SqlSessionFactory primarySqlSessionFactory(@Qualifier("primaryDataSource") DataSource primaryDataSource) throws Exception {
LOGGER.info("====================");
LOGGER.info("primaryDataSource=========" + primaryDataSource);
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(primaryDataSource);
factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/primary/*.xml"));
return factoryBean.getObject();
}
@Bean(name = "primarySqlSessionTemplate")
public SqlSessionTemplate primarySqlSessionTemplate(@Qualifier("primarySqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
@Bean(name = "primaryTransactionManager")
public DataSourceTransactionManager primaryTransactionManager(@Qualifier("primaryDataSource") DataSource primaryDataSource) {
return new DataSourceTransactionManager(primaryDataSource);
}
}
package com.zsx.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.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
@Configuration
@MapperScan(basePackages = {"com.zsx.mapper.second"}, sqlSessionFactoryRef = "secondSqlSessionFactory")
public class MybatisDBSecondConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(MybatisDBSecondConfig.class);
@Bean(name = "secondSqlSessionFactory")
public SqlSessionFactory secondSqlSessionFactory(@Qualifier("secondDataSource") DataSource secondDataSource) throws Exception {
LOGGER.info("====================");
LOGGER.info("secondDataSource=========" + secondDataSource);
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(secondDataSource);
factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/second/*.xml"));
return factoryBean.getObject();
}
@Bean(name = "secondSqlSessionTemplate")
public SqlSessionTemplate secondSqlSessionTemplate(@Qualifier("secondSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
@Bean(name = "secondTransactionManager")
public DataSourceTransactionManager secondTransactionManager(@Qualifier("secondDataSource") DataSource secondDataSource) {
return new DataSourceTransactionManager(secondDataSource);
}
}
package com.zsx.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.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
@Configuration
@MapperScan(basePackages = {"com.zsx.mapper.third"}, sqlSessionFactoryRef = "thirdSqlSessionFactory")
public class MybatisDBThirdConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(MybatisDBThirdConfig.class);
@Bean(name = "thirdSqlSessionFactory")
public SqlSessionFactory sqlSessionFactory(@Qualifier("thirdDataSource") DataSource thirdDataSource) throws Exception {
LOGGER.info("====================");
LOGGER.info("thirdDataSource=========" + thirdDataSource);
SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
factoryBean.setDataSource(thirdDataSource);
factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapper/third/*.xml"));
return factoryBean.getObject();
}
@Bean(name = "thirdSqlSessionTemplate")
public SqlSessionTemplate thirdSqlSessionTemplate(@Qualifier("thirdSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
return new SqlSessionTemplate(sqlSessionFactory);
}
@Bean(name = "thirdTransactionManager")
public DataSourceTransactionManager thirdTransactionManager(@Qualifier("thirdDataSource") DataSource thirdDataSource) {
return new DataSourceTransactionManager(thirdDataSource);
}
}
4. 分别编写对应的数据接口
package com.zsx.mapper.primary;
import com.zsx.entity.User;
import org.springframework.stereotype.Repository;
@Repository("userMapper0")
public interface UserMapper {
User findById(Integer id);
User findById1(Integer id);
}
package com.zsx.mapper.second;
import com.zsx.entity.User;
import org.springframework.stereotype.Repository;
@Repository("userMapper2")
public interface UserMapper {
User findById(Integer id);
}
package com.zsx.mapper.third;
import com.zsx.entity.User;
import org.springframework.stereotype.Repository;
@Repository("userMapper3")
public interface UserMapper {
User findById(Integer id);
}
5. 分别在资源目录下创建键对应的mapper映射文件(resources\mybatis\mapper\primary\primary-user-mapper.xml、resources\mybatis\mapper\second\second-user-mapper.xml、resources\mybatis\mapper\third\third-user-mapper.xml)
5.1 primary-user-mapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zsx.mapper.primary.UserMapper">
<resultMap type="com.zsx.entity.User" id="userResultMap">
<!-- 用id属性来映射主键字段 -->
<id property="id" column="id"/>
<!-- 用result属性来映射非主键字段 -->
<result property="name" column="name"/>
</resultMap>
<select id="findById" resultMap="userResultMap">
SELECT id, name FROM user WHERE id = #{id}
</select>
<select id="findById1" resultMap="userResultMap">
SELECT id, name FROM test1.user WHERE id = #{id}
</select>
</mapper>
5.2 second-user-mapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zsx.mapper.second.UserMapper">
<resultMap type="com.zsx.entity.User" id="userResultMap">
<!-- 用id属性来映射主键字段 -->
<id property="id" column="id"/>
<!-- 用result属性来映射非主键字段 -->
<result property="name" column="name"/>
</resultMap>
<select id="findById" resultMap="userResultMap">
SELECT id, name FROM user WHERE id = #{id}
</select>
</mapper>
5.3 third-user-mapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.zsx.mapper.third.UserMapper">
<resultMap type="com.zsx.entity.User" id="userResultMap">
<!-- 用id属性来映射主键字段 -->
<id property="id" column="id"/>
<!-- 用result属性来映射非主键字段 -->
<result property="name" column="name"/>
</resultMap>
<select id="findById" resultMap="userResultMap">
SELECT id, name FROM user WHERE id = #{id}
</select>
</mapper>
6. 测试类
package com.zsx.test.mapper;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
@ExtendWith(SpringExtension.class)
@SpringBootTest
public class UserMapperTest {
@Autowired
@Qualifier("userMapper0")
private com.zsx.mapper.primary.UserMapper userMapper0;
@Autowired
@Qualifier("userMapper2")
private com.zsx.mapper.second.UserMapper userMapper2;
@Autowired
@Qualifier("userMapper3")
private com.zsx.mapper.third.UserMapper userMapper3;
@Test
void testFindById() {
System.out.println(userMapper0.findById(1));
System.out.println(userMapper2.findById(1));
System.out.println(userMapper3.findById(1));
}
}
7. 运行测试方法,查看测试结果
C:\software\jdk-11.0.3\bin\java.exe -ea -Didea.test.cyclic.buffer.size=1048576 "-javaagent:C:\software\JetBrains\IntelliJ IDEA 2019.1.3\lib\idea_rt.jar=18138:C:\software\JetBrains\IntelliJ IDEA 2019.1.3\bin" -Dfile.encoding=UTF-8 -classpath "C:\software\JetBrains\IntelliJ IDEA 2019.1.3\lib\idea_rt.jar;C:\software\JetBrains\IntelliJ IDEA 2019.1.3\plugins\junit\lib\junit-rt.jar;C:\software\JetBrains\IntelliJ IDEA 2019.1.3\plugins\junit\lib\junit5-rt.jar;D:\repository\org\junit\vintage\junit-vintage-engine\5.3.2\junit-vintage-engine-5.3.2.jar;D:\repository\org\apiguardian\apiguardian-api\1.0.0\apiguardian-api-1.0.0.jar;D:\repository\org\junit\platform\junit-platform-engine\1.3.2\junit-platform-engine-1.3.2.jar;D:\repository\org\junit\platform\junit-platform-commons\1.3.2\ju