spring boot 集成 postgresql mybatis-plus swagger pagehelper
spring boot 集成 postgresql mybatis-plus swagger pagehelper
- 一、前言
- 二、环境配置
- 1.pom.xml
- 2.config文件
- ①:DruidConfig
- ②:MybatisPlusConfig
- ③:SwaggerConfig
- 3.yml文件
- 三、接口代码
- 四、swagger接口测试
- 五、本文案例demo源码
一、前言
spring boot 集成 postgresql mybatis-plus swagger pagehelper,进行简单的增删改查
二、环境配置
1.pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.dongbingya</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>8</java.version>
<knife4j.version>2.0.4</knife4j.version>
<springfox.version>2.9.2</springfox.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<!--mybatis-plus-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.4.0</version>
</dependency>
<!--pageHelper分页-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.2.11</version>
</dependency>
<!-- 阿里数据库连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.18</version>
</dependency>
<!-- Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>${springfox.version}</version>
</dependency>
<!-- knife4j -->
<!-- https://mvnrepository.com/artifact/com.github.xiaoymin/knife4j-spring-boot-starter -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>${knife4j.version}</version>
</dependency>
</dependencies>
<build>
<!-- 注:maven默认是不编译,因此加上如下resources才会生产对应的xml文件 目的:解决mybatis映射关系不对应问题 start =============== -->
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
</resource>
</resources>
<testResources>
<testResource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</testResource>
</testResources>
<!-- 注:maven默认是不编译,因此加上如下resources才会生产对应的xml文件 目的:解决mybatis映射关系不对应问题 end =============== -->
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
2.config文件
①:DruidConfig
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import com.alibaba.druid.support.spring.stat.DruidStatInterceptor;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.aop.support.JdkRegexpMethodPointcut;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
/**
* @author MrDong
* @create 2021/5/25 14:41
* @desc <p> Druid核心配置类 - 注册bean </p> Druid连接池监控平台 http://127.0.0.1:8080/druid/index.html
**/
@Configuration
public class DruidConfig {
@Value("${spring.datasource.loginUsername}")
private String loginUsername;
@Value("${spring.datasource.loginPassword}")
private String loginPassword;
/**
* 配置Druid监控
*
* @param :
* @return: org.springframework.boot.web.servlet.ServletRegistrationBean
*/
@Bean
public ServletRegistrationBean druidServlet() {
// 注册服务
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
// IP白名单(为空表示,所有的都可以访问,多个IP的时候用逗号隔开)
servletRegistrationBean.addInitParameter("allow", "127.0.0.1");
// IP黑名单 (存在共同时,deny优先于allow)
servletRegistrationBean.addInitParameter("deny", "127.0.0.2");
// 设置控制台登录的用户名和密码
servletRegistrationBean.addInitParameter("loginUsername", loginUsername);
servletRegistrationBean.addInitParameter("loginPassword", loginPassword);
// 是否能够重置数据
servletRegistrationBean.addInitParameter("resetEnable", "false");
return servletRegistrationBean;
}
/**
* 配置web监控的filter
*
* @param :
* @return: org.springframework.boot.web.servlet.FilterRegistrationBean
*/
@Bean
public FilterRegistrationBean webStatFilter() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
// 添加过滤规则
Map<String, String> initParams = new HashMap<>(1);
// 设置忽略请求
initParams.put("exclusions", "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*");
filterRegistrationBean.setInitParameters(initParams);
filterRegistrationBean.addInitParameter("profileEnable", "true");
filterRegistrationBean.addInitParameter("principalCookieName", "USER_COOKIE");
filterRegistrationBean.addInitParameter("principalSessionName", "");
filterRegistrationBean.addInitParameter("aopPatterns", "com.example.demo.service");
// 验证所有请求
filterRegistrationBean.addUrlPatterns("/*");
return filterRegistrationBean;
}
/**
* 配置数据源 【 将所有前缀为spring.datasource下的配置项都加载到DataSource中 】
*
* @param :
* @return: javax.sql.DataSource
*/
@Bean(name = "dataSource")
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource dataSource() {
return new DruidDataSource();
}
/**
* 配置事物管理器
*
* @param :
* @return: org.springframework.jdbc.datasource.DataSourceTransactionManager
*/
@Bean(name = "transactionManager")
public DataSourceTransactionManager transactionManager() {
return new DataSourceTransactionManager(dataSource());
}
/**
* ↓↓↓↓↓↓ 配置spring监控 ↓↓↓↓↓↓
* DruidStatInterceptor: druid提供的拦截器
*
* @param :
* @return: com.alibaba.druid.support.spring.stat.DruidStatInterceptor
*/
@Bean
public DruidStatInterceptor druidStatInterceptor() {
DruidStatInterceptor dsInterceptor = new DruidStatInterceptor();
return dsInterceptor;
}
/**
* 使用正则表达式配置切点
*
* @param :
* @return: org.springframework.aop.support.JdkRegexpMethodPointcut
*/
@Bean
@Scope("prototype")
public JdkRegexpMethodPointcut druidStatPointcut() {
JdkRegexpMethodPointcut pointcut = new JdkRegexpMethodPointcut();
pointcut.setPattern("com.dongbing.demo.modules.*.controller.*");
return pointcut;
}
/**
* DefaultPointcutAdvisor类定义advice及 pointcut 属性。advice指定使用的通知方式,也就是druid提供的DruidStatInterceptor类,pointcut指定切入点
*
* @param druidStatInterceptor
* @param druidStatPointcut:
* @return: org.springframework.aop.support.DefaultPointcutAdvisor
*/
@Bean
public DefaultPointcutAdvisor druidStatAdvisor(DruidStatInterceptor druidStatInterceptor, JdkRegexpMethodPointcut druidStatPointcut) {
DefaultPointcutAdvisor defaultPointAdvisor = new DefaultPointcutAdvisor();
defaultPointAdvisor.setPointcut(druidStatPointcut);
defaultPointAdvisor.setAdvice(druidStatInterceptor);
return defaultPointAdvisor;
}
}
②:MybatisPlusConfig
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* @author MrDong
* @create 2021/5/25 11:05
* @desc <p> MybatisPlus配置类 </p>
**/
@EnableTransactionManagement
@Configuration
@MapperScan("com.dongbingya.demo.modules.**.mapper*") // 扫描 Mapper 文件夹 TODO 【注:根据自己的项目结构配置】
public class MybatisPlusConfig {
/**
* 这个是比较新的
* 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
PaginationInnerInterceptor paginationInnerInterceptor = new PaginationInnerInterceptor();
paginationInnerInterceptor.setDbType(DbType.MYSQL);
paginationInnerInterceptor.setOverflow(true);
interceptor.addInnerInterceptor(paginationInnerInterceptor);
return interceptor;
}
@Bean
public ConfigurationCustomizer configurationCustomizer() {
return configuration -> configuration.setUseDeprecatedExecutor(false);
}
}
③:SwaggerConfig
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* @author Mr. Dong
* @create 2022/1/12 16:11
* @desc swagger 配置类
**/
@Configuration
@EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurationSupport {
// 是否开启swagger
@Value("${swagger.enable}")
private boolean enable;
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.dongbingya.demo.modules.system.controller"))
.paths(PathSelectors.any())
.build()
.enable(enable);
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("swagger-bootstrap-ui RESTful APIs")
.description("swagger-bootstrap-ui")
.termsOfServiceUrl("http://localhost:8080/")
.version("1.0")
.build();
}
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
3.yml文件
# 配置端口
server:
port: 8086
servlet:
#context-path: /api
application-display-name: demo
spring:
application:
name: demo
# 配置数据源
datasource: #localhost也叫local,正确解释为:本地服务器。127.0.0.1在系统的正确解释是:本机地址(本机服务器)。尽量用localhost 区别:https://blog.csdn.net/Mr_Maxiansheng/article/details/103192302
#url: jdbc:mysql://localhost:3306/stu?allowMultiQueries=true&useUnicode=true&characterEncoding=UTF8&zeroDateTimeBehavior=convertToNull&useSSL=false # MySQL在高版本需要指明是否进行SSL连接 解决则加上 &useSSL=false
url: jdbc:postgresql://localhost:5432/dongbingya?serverTimezone=Asia/Shanghai&useUnicode=true&characterEncoding=utf8&characterSetResults=utf8&useSSL=false&allowMultiQueries=true
name: demo
username: postgres
password: 123456
driver-class-name: org.postgresql.Driver
# ===================== ↓↓↓↓↓↓ 使用druid数据源 ↓↓↓↓↓↓ =====================
# 连接池类型,druid连接池springboot暂无法默认支持,需要自己配置bean
type: com.alibaba.druid.pool.DruidDataSource
initialSize: 5 # 连接池初始化连接数量
minIdle: 5 # 连接池最小空闲数
maxActive: 20 # 连接池最大活跃连接数
maxWait: 60000 # 配置获取连接等待超时的时间
timeBetweenEvictionRunsMillis: 60000 # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
minEvictableIdleTimeMillis: 300000 # 配置一个连接在池中最小生存的时间,单位是毫秒
validationQuery: SELECT 1 # 连接是否有效的查询语句
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
# 打开PSCache,并且指定每个连接上PSCache的大小
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
removeAbandoned: true
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,【 'stat':监控统计 'wall':用于防火墙,防御sql注入 'slf4j':日志 】
filters: stat,wall,slf4j
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
#useGlobalDataSourceStat: true # 合并多个DruidDataSource的监控数据
loginUsername: admin # SQL监控后台登录用户名
loginPassword: admin # SQL监控后台登录用户密码
# Redis数据源
redis:
# Redis数据库索引(默认为0)
database: 0
# Redis服务器地址
host: 127.0.0.1
# Redis服务器连接端口
port: 6378
# 连接超时时间(毫秒
timeout: 6000
# Redis服务器连接密码(默认为空)
password:
jedis:
pool:
max-active: 1000 # 连接池最大连接数(使用负值表示没有限制)
max-wait: -1 # 连接池最大阻塞等待时间(使用负值表示没有限制)
max-idle: 10 # 连接池中的最大空闲连接
min-idle: 5 # 连接池中的最小空闲连接
main:
allow-bean-definition-overriding: true #当遇到同样名字的时候,是否允许覆盖注册
#thymeleaf
thymeleaf:
mode: LEGACYHTML5
freemarker:
template-loader-path: classpath:/templates
mvc:
static-path-pattern: /static/**
#关闭安全验证
management:
security:
enabled: false
# mybatis-plus相关配置
mybatis-plus:
# xml扫描,多个目录用逗号或者分号分隔(告诉 Mapper 所对应的 XML 文件位置) **表示任意多级目录 *表示多个任意字符
mapper-locations: classpath:**/*Mapper.xml
# 以下配置均有默认值,可以不设置
global-config:
#主键类型 0:"数据库ID自增", 1:"用户输入ID",2:"全局唯一ID (数字类型唯一ID)", 3:"全局唯一ID UUID";
id-type: 0
#字段策略 0:"忽略判断",1:"非 NULL 判断"),2:"非空判断"
field-strategy: 2
#驼峰下划线转换
db-column-underline: true
#刷新mapper 调试神器
refresh-mapper: false
#数据库大写下划线转换
#capital-mode: true
#序列接口实现类配置
#key-generator: com.baomidou.springboot.xxx
#逻辑删除配置
logic-delete-value: 1 # 逻辑已删除值(默认为 1)
logic-not-delete-value: 0 # 逻辑未删除值(默认为 0)
#自定义填充策略接口实现
# meta-object-handler: com.zhengqing.config.MyMetaObjectHandler
#自定义SQL注入器
#sql-injector: com.baomidou.springboot.xxx
configuration:
# 是否开启自动驼峰命名规则映射:从数据库列名到Java属性驼峰命名的类似映射
map-underscore-to-camel-case: true
#解决控制台不打印sql语句问题
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
cache-enabled: false
# 如果查询结果中包含空值的列,则 MyBatis 在映射的时候,为false时不会映射这个字段
call-setters-on-nulls: true
# 这个配置会将执行的sql打印出来,在开发或测试的时候可以用
# log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
# 解决oracle更新数据为null时无法转换报错,mysql不会出现此情况
jdbc-type-for-null: 'null'
swagger:
enable: true
#logging:
# level:
# root: warn
# com.dongbing.demo.modules.system.mapper: trace
# pattern:
# console: '%p%m%n'
# 本地浏览器可以访问本地文件夹的图片
picture:
# 图片访问路径 http://localhost:8085/show/cust20210917161121e936741684c7486fb6b6b30b776c2d28.jpg 需在图片钱加上show
show: /show/**
# 本地映射,图片真实存放路径
up-path: C:/Images/image/
pagehelper:
reasonable: true
support-methods-arguments: true
params: count=countSql
三、接口代码
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dongbingya.demo.modules.comments.result.ResponseVo;
import com.dongbingya.demo.modules.system.entity.Student;
import com.dongbingya.demo.modules.system.service.StudentService;
import com.dongbingya.demo.modules.system.vo.StudentPageParams;
import com.dongbingya.demo.modules.utils.UUIDUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* @author Mr.Dong
* @date 2023/3/28 10:42
* @desc 浏览器访问 http://localhost:8086/doc.html
*/
@RestController
@RequestMapping("/student")
public class StudentController {
@Autowired
private StudentService studentService;
@PostMapping("/getStudentListByPage")
@ApiOperation(value = "学生信息分页查询", httpMethod = "POST",response = Student.class)
public ResponseVo getStudentListByPage(@RequestBody StudentPageParams params){
PageHelper.startPage(params.getPage(),params.getPageSize());
/**
* 在使用PageHelper时,下面的这个查询方法需要用自己手写的sql方法,不能用mybatis、mybatis plus 自带的查询方法
*/
List<Student> list = studentService.getStudentListByPage(params.getStuName(),params.getStuSex());
PageInfo<Student> pageInfo = new PageInfo<Student>(list);
return ResponseVo.success(pageInfo);
}
@PostMapping("/insertStudentInfo")
@ApiOperation(value = "学生信息新增", httpMethod = "POST")
public ResponseVo insertStudentInfo(@RequestBody Student student){
student.setStuNo(UUIDUtil.UUID());
studentService.save(student);
return ResponseVo.ok();
}
@GetMapping("/getStudentInfoByStuNoEcho")
@ApiOperation(value = "根据学生编号查询学生信息,修改数据时数据回显用", httpMethod = "GET")
public ResponseVo getStudentInfoByStuNoEcho(@RequestParam String stuNo){
return ResponseVo.success(studentService.getById(stuNo));
}
@PutMapping("/insertStudentInfo")
@ApiOperation(value = "学生信息修改", httpMethod = "PUT")
public ResponseVo updateStudentInfo(@RequestBody Student student){
LambdaUpdateWrapper<Student> update = Wrappers.lambdaUpdate();
studentService.updateById(student);
return ResponseVo.ok();
}
@DeleteMapping("/deleteStudentInfo")
@ApiOperation(value = "学生信息删除", httpMethod = "DELETE")
public ResponseVo deleteStudentInfo(@RequestParam String stuNo){
studentService.removeById(stuNo);
return ResponseVo.ok();
}
}
四、swagger接口测试
浏览器访问 http://localhost:8086/doc.html
swagger接口文档
五、本文案例demo源码
https://gitee.com/dongbingya/springboot