- 首先创建2个用于测试的数据库,每个数据库中都创建一张user表,建表语句如下:
CREATE TABLE `user` (
`id` bigint(20) NOT NULL,
`name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NULL DEFAULT NULL,
`age` int(11) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci ROW_FORMAT = Dynamic;
- 创建一个spring boot项目,项目结构如下:
- 导入相关的maven依赖:
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
- 编写多数据源配置文件:
spring:
datasource:
# 第一个数据源
first:
# 多数据源配置中url替换成jdbc-url
jdbc-url: jdbc:mysql://localhost:3306/bg-learnsp?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8&useSSL=false
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
# 第二个数据源
second:
jdbc-url: jdbc:mysql://localhost:3306/bg-learnsp-second?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=UTF-8&useSSL=false
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
mybatis:
mapper-locations: classpath:/mapper/**/*.xml # mapper文件位置
logging:
level:
root: info
com.learn.mapper: debug
注意:多数据源配置中,url属性名称需要替换成jdbc-url。
- 初始化数据源:
- first数据源
@Configuration
@MapperScan(basePackages = "com.learn.mapper.first", sqlSessionFactoryRef = "firstSqlSessionFactory")
public class FirstDataSourceConfig {
@Bean(name = "firstDataSource")
// 表示这个数据源是默认数据源
@Primary
// prefix表示参数的前缀
@ConfigurationProperties(prefix = "spring.datasource.first")
public DataSource firstDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "firstSqlSessionFactory")
// 表示这个数据源是默认数据源
@Primary
// @Qualifier表示查找Spring容器中名字为test1DataSource的对象
public SqlSessionFactory firstSqlSessionFactory(@Qualifier("firstDataSource") DataSource datasource)
throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(datasource);
// mapper文件位置
bean.setMapperLocations(
new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/first/**/*.xml"));
return bean.getObject();
}
@Bean("firstSqlSessionTemplate")
// 表示这个数据源是默认数据源
@Primary
public SqlSessionTemplate firstSqlSessionTemplate(
@Qualifier("firstSqlSessionFactory") SqlSessionFactory sessionFactory) {
return new SqlSessionTemplate(sessionFactory);
}
}
- second数据源
@Configuration
@MapperScan(basePackages = "com.learn.mapper.second", sqlSessionFactoryRef = "secondSqlSessionFactory")
public class SecondDataSourceConfig {
@Bean(name = "secondDataSource")
// prefix表示参数的前缀
@ConfigurationProperties(prefix = "spring.datasource.second")
public DataSource secondDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "secondSqlSessionFactory")
// @Qualifier表示查找Spring容器中名字为test1DataSource的对象
public SqlSessionFactory secondSqlSessionFactory(@Qualifier("secondDataSource") DataSource datasource)
throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(datasource);
bean.setMapperLocations(
new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/second/**/*.xml"));
return bean.getObject();
}
@Bean("secondSqlSessionTemplate")
public SqlSessionTemplate secondSqlSessionTemplate(
@Qualifier("secondSqlSessionFactory") SqlSessionFactory sessionFactory) {
return new SqlSessionTemplate(sessionFactory);
}
}
- 编写数据库User实体类
- first数据源
@Data
public class FirstUser {
private Long id;
private String name;
private Integer age;
}
- second数据源
@Data
public class SecondUser {
private Long id;
private String name;
private Integer age;
}
- 创建UserMapper文件:
- first数据源
public interface FirstUserMapper {
/**
* 通过id获取用户信息
*
* @param id
* @return
*/
@Select("select * from user where id = #{id}")
public FirstUser getFirstUserById(Long id);
/**
* 保存用户信息
*
* @param firstUser
* @return
*/
public int insertFirstUser(FirstUser firstUser);
}
- second数据源
public interface SecondUserMapper {
/**
* 通过id获取用户信息
*
* @param id
* @return
*/
@Select("select * from user where id = #{id}")
public SecondUser getSecondUserById(Long id);
/**
* 保存用户信息
*
* @param secondUser
* @return
*/
public int insertSecondUser(SecondUser secondUser);
}
这里Mapper文件使用了注解和xml文件相结合的方式。
- 创建UserMapper相关xml配置文件
- first数据源,FirstUserMapper.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.learn.mapper.first.FirstUserMapper">
<insert id="insertFirstUser">
INSERT INTO USER(ID,NAME, AGE) VALUES(#{id},#{name}, #{age})
</insert>
</mapper>
- second数据源,SecondUserMapper.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.learn.mapper.second.SecondUserMapper">
<insert id="insertSecondUser">
INSERT INTO USER(ID,NAME, AGE) VALUES(#{id},#{name}, #{age})
</insert>
</mapper>
- 编写测试用例:
@SpringBootTest
class SpLearnMybatisMultiDataSourceApplicationTests {
@Autowired
private FirstUserMapper firstUserMapper;
@Autowired
private SecondUserMapper secondUserMapper;
@Test
void testUserMapper() {
FirstUser firstUser = new FirstUser();
firstUser.setId(7777L);
firstUser.setName("我是First数据源保存的");
firstUser.setAge(100);
//保存
firstUserMapper.insertFirstUser(firstUser);
//查询
System.out.println(firstUserMapper.getFirstUserById(7777L));
SecondUser secondUser = new SecondUser();
secondUser.setId(8888L);
secondUser.setName("我是Second数据源保存的");
secondUser.setAge(0);
//保存
secondUserMapper.insertSecondUser(secondUser);
//查询
System.out.println(secondUserMapper.getSecondUserById(8888L));
}
}
- 测试结果:
可以看到使用不同的数据源配置的mapper对象保存,数据成功保存到了不同的数据库中。