springboot+mybatis-plus配置多数据源和分页插件
时间: 2023-12-26 15:56:15 浏览: 139
springboot+Mybatisplus实现多数据源
5星 · 资源好评率100%
配置多数据源:
1. 在pom.xml中添加mybatis-plus和druid依赖:
```xml
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3.1</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.6</version>
</dependency>
```
2. 在application.yml中添加数据源配置:
```yaml
spring:
datasource:
druid:
one:
url: jdbc:mysql://localhost:3306/one?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
two:
url: jdbc:mysql://localhost:3306/two?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
#默认数据源
primary: one
```
3. 在代码中使用@DS注解切换数据源:
```java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@DS("one")
@Override
public User getUserById(Long id) {
return userMapper.selectById(id);
}
@DS("two")
@Override
public User getUserByName(String name) {
return userMapper.selectOne(new QueryWrapper<User>().eq("name", name));
}
}
```
配置分页插件:
1. 在pom.xml中添加分页插件依赖:
```xml
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.3.1</version>
</dependency>
```
2. 在配置类中配置分页插件:
```java
@Configuration
public class MybatisPlusConfig {
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
return paginationInterceptor;
}
}
```
3. 在controller层中使用分页:
```java
@GetMapping("/users")
public IPage<User> getUsers(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
@RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
Page<User> page = new Page<>(pageNum, pageSize);
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
queryWrapper.eq("status", 1);
return userService.page(page, queryWrapper);
}
```
阅读全文