1、Maven依赖
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatisplus.boot.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${druid.version}</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>dynamic-datasource-spring-boot-starter</artifactId>
<version>${dynamic.datasource.boot.version}</version>
</dependency>
2、配置文件
spring:
autoconfigure:
exclude: com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure # 为了某些版本的springboot @SpringBootApplication(exclude= {DataSourceAutoConfiguration.class}) 无法生效
datasource:
dynamic:
primary: master
datasource:
master:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://xxxxxxx:xxxxx/xxxxxx?useUnicode=true&characterEncoding=utf-8&useSSL=false
username: xxxxx
password: xxxxx
user:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://xxxxxx:xxxx/user?useUnicode=true&characterEncoding=utf-8&useSSL=false
username: xxxxxx
password: xxxxxx
initial-size: 5
min-idle: 5
max-active: 20
max-wait: 60000
time-between-eviction-runs-millis: 60000
min-evictable-idle-time-millis: 300000
validation-query: SELECT 1 FROM DUAL
test-while-idle: true
test-on-borrow: false
test-on-return: false
max-pool-prepared-statement-per-connection-size: 30
filters: stat,wall,config
use-global-data-source-stat: true
3、启动类
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.web.servlet.ServletComponentScan;
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
@MapperScan("com.ruqi.travel.adminpanel.mapper")// 你自己项目mapper的位置
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
4.编写实体类和Mapper
4.1 user.java
import lombok.Data;
/**
* user 实体类
*/
@Data
public class User {
private String id;
private String name;
private Integer age;
private String email;
}
4.2 UserMapper.java
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.mybatisplus.entity.User;
/**
* 用户mapper
*/
@DS("user") //这里是配置数据源注解,默认是master
public interface UserMapper extends BaseMapper<User> {
}
注意:如果手动SQL是写在Mapper方法上面用@Select注解的内容里 而不是对应的Mapper.xml,则@DS不能作用用在Mapper上面,只能写在Service上,具体原因请看:坑:Mybatis-Plus 使用 @DS注解 做多数据源切换 mapper代理失败_Carson073的博客-CSDN博客