SpringBoot整合Mybatis-plus多数据源
背景说明:在项目中需要访问多个数据库的时候,我们该怎么办呢?下面我介绍一个极其方便的动态切换数据源的方法。
pom.xml
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.6.5
com.example
demo-spring-mybatisplus
0.0.1-SNAPSHOT
demo-spring-mybatisplus
Demo project for Spring Boot
1.8
org.springframework.boot
spring-boot-starter
org.springframework.boot
spring-boot-starter-test
test
com.baomidou
mybatis-plus-boot-starter
3.5.1
com.baomidou
dynamic-datasource-spring-boot-starter
3.3.2
mysql
mysql-connector-java
8.0.21
com.alibaba
druid-spring-boot-starter
1.2.8
org.projectlombok
lombok
1.18.16
org.springframework.boot
spring-boot-maven-plugin
application.yml
spring:
autoconfigure:
exclude: com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure
datasource:
dynamic:
primary: mysql1 #设置默认数据库源
strict: false #严格匹配数据源,默认为false,true未匹配到指定数据库时抛异常,false使用默认数据源
datasource:
mysql1:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/demo_mybatisplus?serverTimezone=UTC
username: root
password: root
mysql2:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/demo_mybatisplus2?serverTimezone=UTC
username: root
password: root
com.example.demospringmybatisplus.pojo
@Data
@NoArgsConstructor //生成无参构造函数
@AllArgsConstructor //生成全参数构造函数
@ToString
@TableName(value = "user") //指定查询的表名为user
public class User {
// 以下为 mybatis-plus测试
private Integer id;
private String name;
private String password;
private String sex;
private Date createTime;
private Date updateTime;
}
@Data
@NoArgsConstructor //生成无参构造函数
@AllArgsConstructor //生成全参数构造函数
@ToString
@TableName(value = "user") //指定查询的表名为user
public class User2 {
// 以下为 mybatis-plus测试
private Integer id;
private String name;
private String password;
private String email;
}
com.example.demospringmybatisplus.mapper
@DS("mysql1")
@Repository("UserMapper")
public interface UserMapper extends baseMapper {
}
@DS("mysql2")
@Repository("User2Mapper")
public interface User2Mapper extends baseMapper {
}
项目启动类:DemoSpringMybatisplusApplication
@MapperScan("com.example.demospringmybatisplus.mapper")
@SpringBootApplication
public class DemoSpringMybatisplusApplication {
public static void main(String[] args) {
SpringApplication.run(DemoSpringMybatisplusApplication.class, args);
}
}
项目测试类:DemoSpringMybatisplusApplicationTests
@SpringBootTest
class DemoSpringMybatisplusApplicationTests {
@Autowired
UserMapper userMapper;
@Autowired
User2Mapper user2Mapper;
@Test
void contextLoads() {
User user = userMapper.selectById(1);
System.out.println(user.toString());
User2 user2 = user2Mapper.selectById(1);
System.out.println(user2.toString());
}
}
项目运行截图(DemoSpringMybatisplusApplicationTests启动):
项目已经上传到 GitHub 和 Gitee
GitHub:demo-spring-mybatisplus
Gitee:demo-spring-mybatisplus