![cover](https://img-blog.csdnimg.cn/img_convert/aa9364ebcbf249c4b2ff3d4102563ad9.png)
Mybatis-Plus项目基础
SpringBoot项目准备,mybatis-plus基础使用,分页与接口文档插件的使用。
·
创建Springboot项目
阿里云Spring Server URL : http://start.aliyun.com
Spring Initializr - SpringBoot Server URL : http://start.spring.io
SpringBoot Maven依赖
<?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>
<groupId>com.sybkl</groupId>
<artifactId>TestBackEnd</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>TestBackEnd</name>
<description>TestBackEnd</description>
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>2.3.12.RELEASE</spring-boot.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</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>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.25</version>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>3.5.3</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.16</version>
</dependency>
<!-- mybatis-plus 代码生成器-->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-generator</artifactId>
<version>3.5.3.1</version>
</dependency>
<!-- 在mybatis-plus的代码生成器中需要导入freemarker的依赖-->
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>${spring-boot.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>${spring-boot.version}</version>
<configuration>
<mainClass>com.sybkl.testbackend.TestBackEndApplication</mainClass>
<skip>true</skip>
</configuration>
<executions>
<execution>
<id>repackage</id>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
说明:使用mybatis-plus可以节约我们大量的代码,尽量不要同时导入mybatis和mybatis-plus。会引起包冲突
以下是application.properties文件配置数据库连接,个人建议使用application.yaml,yaml配置文件的使用方法相对更加主流。
# 数据源配置
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?useSSL=false&userUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
application.yaml文件配置数据库连接
spring:
datasource:
url: jdbc:mysql://localhost:3306/my_db01?useSSL=false&characterEncoding=UTF-8&useUnicode=true
username: root
password: passwd
driver-class-name: com.mysql.cj.jdbc.Driver
server:
port: 10029 # 数据端口
mybatis-plus:
mapper-locations:
classpath: mapper/*.xml
configuration:
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl # SQL语句格式化输出
# map-underscore-to-camel-case: false #关闭下划线映射驼峰转换
增删改查案例
编写PoJo类(Entity)
package com.sybkl.bigdatastudentmybatisplus.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
@Data
@TableName("student_list")
public class Table {
@TableId
private String id;
@TableField("class_name")
private String className;
private String name;
}
编写Mapper类(Mapper)继承BaseMapper< Entity >
package com.sybkl.bigdatastudentmybatisplus.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.sybkl.bigdatastudentmybatisplus.entity.Table;
public interface TableMapper extends BaseMapper<Table> {
}
需要在启动类或者配置类中扫描(MapperScan) mapper包
动态拼接SQL语句
由mapper标签开始,由/mapper结束,可以把它想成一个空间,是映射文件
属性namespace:空间名,主要在代理中使用。这个namespace是唯一的。
这里把mapper标签和接口联系在一起了,namespace=写接口路径,映射文件要和接口在同一目录下
<?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="com.sybkl.testbackend.mapper.UserMapper">
<update id="update">
update user
<set>
<if test="username != null">
username=#{username},
</if>
<if test="password != null">
password=#{password}
</if>
</set>
<where>
username=#{username}
</where>
</update>
</mapper>
编写服务层(Service)继承 IService< Entity>
package com.sybkl.bigdatastudentmybatisplus.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.sybkl.bigdatastudentmybatisplus.entity.Table;
public interface TableService extends IService<Table> {
}
Service ServiceImpl(继承ServiceImpl< Mapper,Entity> 实现Service)
package com.sybkl.bigdatastudentmybatisplus.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sybkl.bigdatastudentmybatisplus.entity.Table;
import com.sybkl.bigdatastudentmybatisplus.mapper.TableMapper;
import com.sybkl.bigdatastudentmybatisplus.service.TableService;
import org.springframework.stereotype.Service;
@Service
public class TableServiceImpl extends ServiceImpl<TableMapper, Table> implements TableService {
}
编写控制层
package com.sybkl.bigdatastudentmybatisplus.controller;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sybkl.bigdatastudentmybatisplus.entity.Table;
import com.sybkl.bigdatastudentmybatisplus.service.TableService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
@RestController
@RequestMapping("/table")
public class TableController {
@Autowired
private TableService tableService;
@GetMapping("/all")
public List<Table> findAllStudent() {
return tableService.list();
}
@GetMapping("/page/{pageNum}/{pageSize}")
public IPage<Table> findPage(@PathVariable Integer pageNum, @PathVariable Integer pageSize) {
IPage<Table> page = new Page<>(pageNum, pageSize);
QueryWrapper<Table> queryWrapper = new QueryWrapper<>();
return tableService.page(page, queryWrapper);
}
@GetMapping("/page")
public IPage<Table> findPage(@RequestParam Integer pageNum, @RequestParam Integer pageSize, @RequestParam String input) {
IPage<Table> page = new Page<>(pageNum, pageSize);
QueryWrapper<Table> queryWrapper = new QueryWrapper<>();
//通过学生姓名或者班级进行模糊查询
queryWrapper.like("name", input).or().like("class_name", input).or().like("id", input);
queryWrapper.orderByAsc("id");
return tableService.page(page, queryWrapper);
}
//新增
@PostMapping
public boolean saveStudent(@RequestBody Table table) {
return tableService.save(table);
}
//修改
@PutMapping
public boolean updateStudent(@RequestBody Table table) {
return tableService.updateById(table);
}
//删除
@DeleteMapping("/{id}")
public boolean deleteStudent(@PathVariable String id) {
return tableService.removeById(id);
}
//批量删除
@PostMapping("/delete/batch")
public boolean deleteBatchStudentInfo(@RequestBody List<String> ids) {
return tableService.removeByIds(ids);
}
}
分页插件
import com.baomidou.mybatisplus.annotation.DbType;
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;
@Configuration
@MapperScan("com.sybkl.bigdatastudentmybatisplus.mapper")
public class MybatisPlusConfig {
/**
* 新的分页插件,一缓和二缓遵循mybatis的规则,需要设置 MybatisConfiguration#useDeprecatedExecutor = false 避免缓存出现问题(该属性会在旧插件移除后一同移除)
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
return interceptor;
}
}
后端跨域
该方法引用于 程序员青戈
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
@Configuration
public class CorsConfig {
// 当前跨域请求最大有效时长。这里默认1天
private static final long MAX_AGE = 24 * 60 * 60;
@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOrigin("http://localhost:8080"); // 1 设置访问源地址
corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头
corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法
corsConfiguration.setMaxAge(MAX_AGE);
source.registerCorsConfiguration("/**", corsConfiguration); // 4 对接口配置跨域设置
return new CorsFilter(source);
}
}
Swagger2接口文档
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.0</version>
</dependency>
以下配置项代码swagger3.0版本不可用
//接口文档访问地址
http://localhost:10029/swagger-ui.html
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
/**
* 创建API应用
* apiInfo() 增加API相关信息
* 通过select()函数返回一个ApiSelectorBuilder实例,用来控制哪些接口暴露给Swagger来展现,
* 本例采用指定扫描的包路径来定义指定要建立API的目录。
* @return
*/
@Bean
public Docket restApi() {
return new Docket(DocumentationType.SWAGGER_2)
.groupName("标准接口")
.apiInfo(apiInfo("Spring Boot中使用Swagger2构建RESTful APIs", "1.0"))
.useDefaultResponseMessages(true)
.forCodeGeneration(false)
.select()
.apis(RequestHandlerSelectors.basePackage("com.sybkl.testbackend.controller"))
.paths(PathSelectors.any())
.build();
}
/**
* 创建该API的基本信息(这些基本信息会展现在文档页面中)
* 访问地址:http://localhost:10029/swagger-ui.html
* @return
*/
private ApiInfo apiInfo(String title, String version) {
return new ApiInfoBuilder()
.title(title)
.description("世间万千景致有大美,等我千万年,不可辜负。")
// .termsOfServiceUrl("https://blog.csdn.net/xqnode")
// .contact(new Contact("xqnode", "https://blog.csdn.net/xqnode", "xiaqingweb@163.com"))
.version(version)
.build();
}
}
更新:Swagger3及knife4j
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
/**
* swagger3整合 knife4j 优化体验
* 访问方式:
* http://{ip}:{port}/doc.html,访问方式和之前的保持一致,如果项目中配置拦截器等,需要放开doc.html静态资源
* http://localhost:10029/doc.html
*/
@Configuration
public class SwaggerConfig {
@Bean
public Docket desertsApi() {
return new Docket(DocumentationType.OAS_30)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.myspring01.controller")) //配置扫描路径
.paths(PathSelectors.any())
.build()
.groupName("desertsGroup")
.enable(true); // 配置是否开启swagger
}
// api基本信息
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Swagger3接口文档")
.description("继续看风景去,世间万千景致有大美,等我千万年,不可辜负。")
.contact(new Contact("山渐青", "http://mail.qq.com", "sybkl@qq.com")) //作者信息
.version("1.0")
.build();
}
}
更多推荐
所有评论(0)