前言

本篇说一下SpringBoot如何整合druid作为连接池,以及用mybatis-plus做持久层。
用到的版本号如下

名称 版本号
SpringBoot 2.1.1.RELEASE
druid-spring-boot-starter 1.1.10
mybatis-plus-boot-starter 3.0.6

例子里使用一个user表,直接利用mybatis-plus提供的接口进行增删改查操作

CREATE TABLE `user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`name` varchar(30) DEFAULT NULL COMMENT '姓名',
`age` int(11) DEFAULT NULL COMMENT '年龄',
`email` varchar(50) DEFAULT NULL COMMENT '邮箱',
`phone` varchar(45) DEFAULT NULL,
`userEvaluation` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin

添加依赖

首先,在pom.xml添加以下的依赖

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.10</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.0.6</version>
</dependency>

添加相关配置

在application.yml中增加以下配置

#数据库配置
spring:
datasource:
druid:
#连接信息
url: jdbc:mysql://localhost:3306/test
username: root
password: 123456
driver-class-name: com.mysql.cj.jdbc.Driver
#连接池配置
min-idle: 5
initial-size: 5
max-active: 20
# 配置获取连接等待超时的时间
max-wait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
time-between-eviction-runs-millis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
min-evictable-idle-time-millis: 30000
validation-query: SELECT 1 FROM DUAL
test-while-idle: true
test-on-borrow: false
test-on-return: false
#监控
filter:
wall:
enabled: true

#mybatis-plus配置
mybatis-plus:
#xml地址
mapper-locations:
- classpath:mapper/*.xml
#实体扫描
type-aliases-package: top.wqp0010.s1.demo.entity.UserEntity

代码

准备工作完毕,开始写代码。总体结构如下

代码结构
代码结构

映射xml

在resources/mapper里新增一个UserMapper.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="top.wqp0010.s1.demo.mapper.UserMapper">

</mapper>

这里并没有写实际的方法,本例我们主要用mybatis-plus提供的方法进行操作,后续再加自己的方法进来

配置类

新增一个mybatis-plus的配置类,指定要扫描的包以及定义分页插件

@Configuration
@MapperScan("top.wqp0010.s1.demo.mapper*")
public class MybatisPlusConfig {
/**
* mybatis-plus分页插件<br>
* 文档:http://mp.baomidou.com<br>
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
return paginationInterceptor;
}
}

新增一个druid的配置类

@Configuration
public class DruidConfig {

private static final Logger log = LoggerFactory.getLogger(DruidConfig.class);

@Bean
public ServletRegistrationBean druidServlet() {
log.info("init Druid Servlet Configuration ");
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean();
servletRegistrationBean.setServlet(new StatViewServlet());
servletRegistrationBean.addUrlMappings("/druid/*");
Map<String, String> initParameters = new HashMap<String, String>();
initParameters.put("loginUsername", "admin");// 用户名
initParameters.put("loginPassword", "admin");// 密码
initParameters.put("resetEnable", "false");// 禁用HTML页面上的“Reset All”功能
initParameters.put("allow", ""); // IP白名单 (没有配置或者为空,则允许所有访问)
//initParameters.put("deny", "192.168.20.38");// IP黑名单 (存在共同时,deny优先于allow)
servletRegistrationBean.setInitParameters(initParameters);
return servletRegistrationBean;
}

@Bean
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
filterRegistrationBean.setFilter(new WebStatFilter());
filterRegistrationBean.addUrlPatterns("/*");
filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
return filterRegistrationBean;
}

}
实体类

定义UserEntity,这个类和数据库user表对应。
这里同时展示了如何映射表名以及表字段和类字段名不同时的处理

/**
* 数据库表名为"user",用@TableName映射
*/
@TableName("user")
@Data
public class UserEntity {

/**
* 表主键 此处需要设置为数据库ID自增
*/
@TableId(type = IdType.AUTO)
private long id;
private String name;
private int age;
private String email;
private String phone;
/**
* 此处故意用了类字段名和数据库列明不相符
* 可以用@TableField注解来表示
*/
@TableField("userEvaluation")
private String evaluation;
}
Mapper类

定义UserMapper接口,主要是继承了mybatis-plus的BaseMapper接口,没有定义自己的方法

public interface UserMapper extends BaseMapper<UserEntity> {

}
Service接口

定义IUserService接口,主要是继承mybatis-plus的IService接口,同样没有自己的实现

public interface IUserService extends IService<UserEntity> {

}

UserServiceImpl 实现类

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements IUserService {

}
Controller

可以看到,上面我们定义的Mapper和Service都是空的,并没有实现具体的方法。现在我们利用mybatis-plus预置的接口实现增删改查

@RestController
@Slf4j
public class UserController {

@Autowired
IUserService userService;

@RequestMapping("/user/add")
public String addUser() {
//这里为了测试方便 直接产生了一些随机字符串作为用户参数
UserEntity userEntity = new UserEntity();
userEntity.setName(RandomStringUtils.randomAlphabetic(5));
userEntity.setAge(new Random().nextInt(100));
userEntity.setEmail(RandomStringUtils.randomAlphanumeric(5) + "@test.com");
userEntity.setPhone("18" + RandomStringUtils.randomNumeric(9));
userEntity.setEvaluation(RandomStringUtils.randomAlphanumeric(20));
userService.save(userEntity);
return "success insert user = " + JSON.toJSONString(userEntity);
}
@RequestMapping("/user/remove")
public String removeUser(@RequestParam("id") int id) {
userService.removeById(id);
return "success delete userId = " + id;
}
@RequestMapping("/user/update")
public String updateUser(@RequestParam("id") int id) {
//为了测试方便,属性值都再次随机赋值
UserEntity userEntity = new UserEntity();
userEntity.setId(id);
userEntity.setName(RandomStringUtils.randomAlphabetic(5));
userEntity.setAge(new Random().nextInt(100));
userEntity.setEmail(RandomStringUtils.randomAlphanumeric(5) + "@test.com");
userEntity.setPhone("18" + RandomStringUtils.randomNumeric(9));
userEntity.setEvaluation(RandomStringUtils.randomAlphanumeric(20));
userService.updateById(userEntity);
return "success update user = " + JSON.toJSONString(userEntity);
}
查单条记录
@RequestMapping("/user/info")
public UserEntity getUser(@RequestParam("id") int id) {
UserEntity userEntity = userService.getById(id);
return userEntity;
}
分页查询
@RequestMapping("/user/list")
public IPage getUserList(Page page) {
page.setDesc("name");
IPage iPage = userService.page(page);
return iPage;
}

浏览器访问http://localhost:8080/user/list?size=3&current=1
返回的结果即是根据数据库name字段倒叙的分页结果,是不是很方便

打开http://localhost:8080/druid/即可看到druid的监控页

参考

  1. druid官网
  2. mybatis-plus官网