今天我们主要讲在实际开发中所用到的一些方法,不知道怎么整合的可以看我上一篇博客
项目已已上传gitee,请移步gitee下载完整项目
SpringBoot快速集成MyBatis-plus—(第一篇)
最终目录结构

整合Swagger文档 引入坐标依赖
<!--swagger-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
在当前目录下创建一个util处理Swagger文档
entity
package com.gxh.modules.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.io.Serializable;
import java.util.Objects;
@TableName("sys_user")//mybatisPlus 注解:映射表名
@Data// lombok代码简化注解,包装Get/Set/构造器
public class SysUser implements Serializable {
//@TableId(type = IdType.ASSIGN_ID) //雪花算法--->MyBatisPlus 支持的Id策略
//@TableId(type = IdType.ASSIGN_UUID) //雪花算法_不含中划线的UUID--->MyBatisPlus 支持的Id策略
//@TableId(type = IdType.ID_WORKER_STR) //利用了雪花算法--->MyBatisPlus 支持的Id策略
/**ID*/
@TableId(type = IdType.AUTO) //自增--->MyBatisPlus 支持的Id策略
private Integer id;
/**用户名*/
private String username;
/**密码*/
private String password;
//请不要在意单词拼写是否正确
//虚拟字段-代表在数据库中不存在(不会被MybatisPlus抛出Know Null Column异常)
@TableField(exist = false)//Type Is boolean(there defaultValue is true)
private String note;
/**
* 重写父类Object 提供的 toString方法,方便测试
* @return
*/
@Override
public String toString() {
return "SysUser{" +
"id='" + id + '\'' +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SysUser sysUser = (SysUser) o;
return Objects.equals(id, sysUser.id) &&
Objects.equals(username, sysUser.username) &&
Objects.equals(password, sysUser.password);
}
@Override
public int hashCode() {
return Objects.hash(id, username, password);
}
}
附上SwaggerConfig
```java
package com.gxh.modules.util;
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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
/**
* @Author gxh
* @Data 2021/8/23
*/
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.pathMapping("/")
.select()
.apis(RequestHandlerSelectors.basePackage("com.gxh.modules.controller"))
.paths(PathSelectors.any())
.build().apiInfo(new ApiInfoBuilder()
.title("SpringBoot-MyBatisPlus")
.description("MyBatis-Plus在开发中常用的方法")
.version("1.0")
.licenseUrl("http://www.lxito.com")
.build());
}
}
在SpringBoot启动类打开Swagger文档
package com.gxh;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.EnableScheduling;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.net.InetAddress;
/***
* @author gxh
* @date 2021-8-21
*/
@EnableSwagger2 //开启swagger文档
@EnableScheduling //开启异步
@SpringBootApplication
public class SpringBootAndMpApplication {
public static void main(String[] args) throws Exception{
Long s1 = System.currentTimeMillis();
ConfigurableApplicationContext application = SpringApplication.run(SpringBootAndMpApplication.class, args);
Long s2 = System.currentTimeMillis();
Environment env = application.getEnvironment();
String ip = InetAddress.getLocalHost().getHostAddress();
String port = env.getProperty("server.port");
String path = env.getProperty("server.servlet.context-path");
System.out.println("=======================================>");
System.out.println("启动耗时=======>"+(s2-s1));
System.out.println("Local:http://localhost:" + port + "/swagger-ui.html");
System.out.println("serve start-up success");
System.out.println("=======================================>");
}
}
定义Result
package com.gxh.modules.constant;
/**
* 响应结果 常量接口
* @Author gxh
* @Data 2021/8/23
*/
// interface 不会继承 Object,所有作为常量效率会好点.
public interface ResultMessageConstant {
/**添加成功*/
//接口常量默认就是被 public static final String 修饰
String MESSAGE_ADD_SUCCESS = "添加成功";
/**200*/
String MESSAGE_SUCCESS_200 = "200";
/**删除成功*/
String MESSAGE_DEL_SUCCESS = "删除成功";
}
1,使用MyBatisPlus的分页列表查询
/***
* 使用MybatisPlus QueryWapper 分页查询
* @return
*/
@GetMapping("/pageList")
public Map<String,Object> pageList(@RequestParam(value = "pageNo",defaultValue = "1") Integer pageNo,
@RequestParam(value = "pageSize",defaultValue = "10") Integer pageSize){
QueryWrapper<SysUser> query = new QueryWrapper<SysUser>();
IPage<SysUser> page = new Page<SysUser>(pageNo,pageSize);
IPage<SysUser> pageList = sysUserService.page(page, query);
result.put("code",ResultMessageConstant.MESSAGE_SUCCESS_200);
result.put("success",true);
result.put("data",pageList);
return result;
}
2.使用MyBatisPlus的不分页list查询
/**
* 不分页list查询
* @return
*/
@GetMapping("/list")
public Map<String,Object> userList(){
List<SysUser> users = this.sysUserService.list();
result.put("userList",users);
return result;
}
3.自定义添加
/**
* 添加用户 1
* 使用自定义SQL + DTO
* @param userDto
* @return
*/
@PostMapping("/addByDto")
public Map<String,Object> addByDto(@RequestBody UserDto userDto){
//调用业务层自定义的添加方法
boolean isFlag = this.sysUserService.insertUser(userDto);
if (isFlag){
result.put("code",ResultMessageConstant.MESSAGE_SUCCESS_200);
result.put("success",true);
result.put("msg", ResultMessageConstant.MESSAGE_ADD_SUCCESS);
result.put("data",userDto);
}
return result;
}
3.1接口层
/**
* 添加用户
* @param userDto
* @return
*/
boolean insertUser(UserDto userDto);
3.1.1接口实现层
@Override
public boolean insertUser(UserDto userDto) {
boolean isFlag = false;
Integer count = this.sysUserMapper.insertUserByDto(userDto);
if (null !=count || count>0){
isFlag = true;
}
return isFlag;
}
4.Dao(Mapper)层
/**
* 添加用户
* @param userDto
* @return
*/
Integer insertUserByDto(@Param("userDto") UserDto userDto);
4.1 xml映射
<insert id="insertUserByDto" parameterType="com.gxh.modules.entity.dto.UserDto">
insert into sys_user(`username`,`password`)
values (#{userDto.username},#{userDto.password})
</insert>
5.使用MyBatisPlus的save方法进行添加操作
/**
* 添加用户 2
* 使用MyBatisPlus + entity(SysUser)
* @param sysUser
* @return
*/
@PostMapping("/add")
public Map<String,Object> add(@RequestBody SysUser sysUser){
boolean save = sysUserService.save(sysUser);
//更新
//sysUserService.update(sysUser);
if (save){
result.put("code",ResultMessageConstant.MESSAGE_SUCCESS_200);
result.put("success",true);
//这里使用一下 当时SysUser定义的虚拟字段 SysUser note(虚拟字段,不存在于数据表中)
sysUser.setNote("添加成功");
result.put("sysUser.note", sysUser.getNote());
result.put("data",sysUser);
}
return result;
}
6.使用MyBatisPlus的removeId放法进行删除操作
/***
* 根据id删除信息
* @param id
* @return
*/
@GetMapping("deleteById")
public Map<String,Object> deleteById(@RequestParam("id") Integer id){
boolean isDel = sysUserService.removeById(id);
if (isDel){
result.put("code",ResultMessageConstant.MESSAGE_SUCCESS_200);
result.put("success",true);
result.put("msg", ResultMessageConstant.MESSAGE_DEL_SUCCESS);
}
return result;
}
7.使用MyBatisPlus的removeByIds方法进行批量删除
/***
* MyBatisPlus 批量删除
* @param id
* @return
*/
@GetMapping("deleteByIds")
public Map<String,Object> deleteByIds(@RequestParam("id") String id){
List<String> idList = Arrays.asList(id.split(","));
boolean isDel = this.sysUserService.removeByIds(idList);
if (isDel){
result.put("code",ResultMessageConstant.MESSAGE_SUCCESS_200);
result.put("success",true);
result.put("msg", ResultMessageConstant.MESSAGE_DEL_SUCCESS);
}
return result;
}
8.使用自定义的批量删除方法
8.1controller
/***
* 自定义SQL 批量删除
* @param id
* @return
*/
@GetMapping("deleteBatch")
public Map<String,Object> deleteBatch(@RequestParam("id") String id){
List<String> idList = Arrays.asList(id.split(","));
this.sysUserService.deleteBatchByIds(idList);
result.put("code",ResultMessageConstant.MESSAGE_SUCCESS_200);
result.put("success",true);
result.put("msg", ResultMessageConstant.MESSAGE_DEL_SUCCESS);
return result;
}
8.2 Service层
/**
* 自定义SQL 批量删除
* @param idList
*/
@Async//Spring 的异步注解
//异步执行
//使用此注解需要在 启动类上开启 @EnableScheduling
void deleteBatchByIds(List<String> idList);
8.2.1ServiceImpl(业务实现层)
@Override
public void deleteBatchByIds(List<String> idList) {
sysUserMapper.deleteBatchByIds(idList);
}
8.3Dao(Mapper)层
/**
* 通过 id 集合批量删除
* @param idList
*/
void deleteBatchByIds(@Param("idList") List<String> idList);
8.3.1xml映射
<!--通过id 集合批量删除-->
<delete id="deleteBatchByIds" parameterType="java.lang.String">
delete from `sys_user`
<where>
<if test="idList !=null and idList.size() > 0">
id in
<foreach collection="idList" item="item" open="(" separator="," close=")">
#{item}
</foreach>
</if>
</where>
</delete>