springboot3整合druid mybatisplus
时间: 2023-10-06 15:05:50 浏览: 131
在Spring Boot项目中整合Druid和MyBatis Plus可以提供非常好的数据库访问性能和可维护性。下面是一些简单的步骤:
1. 添加依赖
在pom.xml中添加以下依赖:
```xml
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>{druid-version}</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>{mybatis-plus-version}</version>
</dependency>
```
2. 配置数据源
在application.properties或application.yml文件中添加以下配置:
```yml
spring:
datasource:
url: jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&useSSL=false&serverTimezone=Asia/Shanghai
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
# druid 连接池配置
druid:
initial-size: 2
min-idle: 1
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
pool-prepared-statements: true
max-pool-prepared-statement-per-connection-size: 20
filters: stat, wall, log4j
connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
```
3. 配置MyBatis Plus
在配置类中添加以下配置:
```java
@Configuration
@MapperScan("com.example.mapper")
public class MybatisPlusConfig {
@Bean
public PaginationInterceptor paginationInterceptor() {
return new PaginationInterceptor();
}
}
```
这里使用了MyBatis Plus的分页插件。
4. 创建Mapper
创建Mapper接口并使用MyBatis Plus的注解:
```java
@Mapper
public interface UserMapper extends BaseMapper<User> {
}
```
5. 测试
创建Controller并测试:
```java
@RestController
@RequestMapping("/users")
public class UserController {
@Autowired
private UserMapper userMapper;
@GetMapping("")
public List<User> list() {
return userMapper.selectList(null);
}
}
```
这样就完成了Druid和MyBatis Plus的整合。
阅读全文