MyBatisPlus是MyBatis的完善补充,可以更好的实现分页等功能。下面开始演示一个简单的例子,如何查看返回列表
一、返回一个List
基于上一章节的例子
1.1、创建BannerBO
区别于MyBatis,需要增加@TableName和@TableId,这点跟JPA相似,在model下创建BO
package io.github.talelin.latticy.model;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Getter;
import lombok.Setter;
import java.util.Date;
@Getter
@Setter
@TableName("banner")
public class BannerDO {
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
private String name;
private String title;
private String description;
private String img;
@JsonIgnore
private Date createTime;
@JsonIgnore
private Date updateTime;
@JsonIgnore
@TableLogic
private Date deleteTime;
}
1.2、创建BannerMapper
extends BaseMapper,继承后就不需要写xml的sql
package io.github.talelin.latticy.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import io.github.talelin.latticy.model.BannerDO;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface BannerMapper extends BaseMapper<BannerDO> {
List<BannerDO> getAllBanners();
long insertBanner(BannerDO bannerDO);
@Select("SELECT * FROM banner")
List<BannerDO> getAllBanners1();
}
1.3、创建Service的接口和方法
接口:TestSleeveService
package io.github.talelin.latticy.service;
import io.github.talelin.latticy.model.BannerDO;
import java.util.List;
public interface TestSleeveService {
public List<BannerDO> getBanners();
public long insertBanner();
public List<BannerDO> getBanners2();
public List<BannerDO> getBannersList();
}
实现类TestSleeveImpl:
直接使用this.bannerMapper.selectList即可取得列表数据。
package io.github.talelin.latticy.service.impl;
import io.github.talelin.latticy.mapper.BannerMapper;
import io.github.talelin.latticy.model.BannerDO;
import io.github.talelin.latticy.service.TestSleeveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class TestSleeveImpl implements TestSleeveService {
/* 在mapper创建BannerMapper接口,类似于JPA的Repository*/
@Autowired
private BannerMapper bannerMapper;
public List<BannerDO> getBanners() {
return this.bannerMapper.getAllBanners();
}
public List<BannerDO> getBanners2() {
return this.bannerMapper.getAllBanners1();
}
public long insertBanner() {
BannerDO bannerDO = new BannerDO();
bannerDO.setName("NewBanner");
bannerDO.setTitle("NewBannerTitle");
bannerMapper.insertBanner(bannerDO);
return bannerDO.getId();
}
public List<BannerDO> getBannersList() {
return this.bannerMapper.selectList(null);
}
}
1.4、创建Controller(test4)
package io.github.talelin.latticy.controller.v1;
import io.github.talelin.latticy.model.BannerDO;
import io.github.talelin.latticy.service.TestSleeveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RequestMapping("/v1/test")
@RestController
public class TestSleeveController {
@Autowired
private TestSleeveService testSleeveService;
@GetMapping("/test1")
public List<BannerDO> test1() {
return testSleeveService.getBanners();
}
@GetMapping("/test2")
public long test2() {
return testSleeveService.insertBanner();
}
@GetMapping("/test3")
public List<BannerDO> test3() {
return testSleeveService.getBanners2();
}
@GetMapping("/test4")
public List<BannerDO> test4() {
return testSleeveService.getBannersList();
}
}
二、返回一个分页List
2.1 创建BannerBO(与1.1相同)
2.2 创建BannerMapper (与1.2相同)
2.3创建一个分页PageResponseVO
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class PageResponseVO<T> {
private Integer total;
private List<T> items;
private Integer page;
private Integer count;
}
2.4 创建MyBatis分页公共类
创建在项目中创建common/mybatis/Page
package io.github.talelin.latticy.common.mybatis;
/**
* 为和其他端保持一致
* 重写 MyBatis-Plus 分页对象,将起始页从 1 改为 0
*
* @author Juzi@TaleLin
*/
public class Page<T> extends com.baomidou.mybatisplus.extension.plugins.pagination.Page<T> {
private static final long serialVersionUID = -2183463672525305273L;
/**
* 该构造方法使得 current 总为 0
*/
public Page() {
super.setCurrent(0);
}
public Page(int current, int size) {
this(current, size, 0);
}
public Page(int current, int size, int total) {
this(current, size, total, true);
}
public Page(int current, int size, boolean isSearchCount) {
this(current, size, 0, isSearchCount);
}
/**
* 该构造方法将小于 0 的 current 置为 0
*
* @param current 当前页
* @param size 每页显示条数,默认 10
* @param total 总数
* @param isSearchCount 是否进行 count 查询
*/
public Page(int current, int size, int total, boolean isSearchCount) {
super(current, size, total, isSearchCount);
if (current < 0) {
current = 0;
}
super.setCurrent(current);
}
@Override
public boolean hasPrevious() {
return super.getCurrent() > 0;
}
@Override
public boolean hasNext() {
return super.getCurrent() + 1 < this.getPages();
}
/**
* 重写计算偏移量,将分页从第 0 开始
*
* @return 偏移量
*/
@Override
public long offset() {
return getCurrent() > 0 ? super.getCurrent() * getSize() : 0;
}
}
2.5、创建Service接口和实现类
2.5.1 BannerService接口
package io.github.talelin.latticy.service;
import io.github.talelin.latticy.model.BannerDO;
import io.github.talelin.latticy.vo.PageResponseVO;
public interface BannerService {
public PageResponseVO<BannerDO> getBanners(Integer page,Integer count);
}
2.5.2 BannerServiceImpl实现类
package io.github.talelin.latticy.service.impl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.github.talelin.latticy.common.mybatis.Page;
import io.github.talelin.latticy.mapper.BannerMapper;
import io.github.talelin.latticy.model.BannerDO;
import io.github.talelin.latticy.service.BannerService;
import io.github.talelin.latticy.vo.PageResponseVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class BannerServiceImpl implements BannerService {
@Autowired
private BannerMapper bannerMapper;
public PageResponseVO<BannerDO> getBanners(Integer page,Integer count){
Page<BannerDO> pager = new Page<>(page,count);
IPage<BannerDO> paging = bannerMapper.selectPage(pager, null);
return new PageResponseVO<BannerDO>((int)paging.getTotal(), paging.getRecords(), (int)paging.getCurrent(), (int)paging.getSize());
}
}
2.6、创建Controller
package io.github.talelin.latticy.controller.v1;
import io.github.talelin.latticy.model.BannerDO;
import io.github.talelin.latticy.service.BannerService;
import io.github.talelin.latticy.vo.PageResponseVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
@RequestMapping("/v1/banner")
@RestController
@Validated
public class BannerController {
@Autowired
private BannerService bannerService;
@GetMapping("/page")
public PageResponseVO<BannerDO> getBanners(
@RequestParam(required = false, defaultValue = "0")
@Min(value = 0) Integer page,
@RequestParam(required = false, defaultValue = "10")
@Min(value = 1) @Max(value = 30) Integer count
){
return bannerService.getBanners(page,count);
}
}
三、MyBatisPlus更新例子
3.1在model下创建一个BannerBO(与1.1一致)
3.2在Mapper下创建一个接口BannerMapper(与1.2一致)
3.3创建Service接口和实现类
3.3.1BannerService接口追加update
package io.github.talelin.latticy.service;
import io.github.talelin.latticy.dto.BannerDTO;
import io.github.talelin.latticy.model.BannerDO;
import io.github.talelin.latticy.vo.PageResponseVO;
import io.github.talelin.latticy.vo.UpdatedVO;
public interface BannerService {
public PageResponseVO<BannerDO> getBanners(Integer page,Integer count);
public void update(BannerDTO dto, Integer id);
}
3.3.2实现方法类BannerServiceImpl追加update
package io.github.talelin.latticy.service.impl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.github.talelin.autoconfigure.exception.NotFoundException;
import io.github.talelin.latticy.common.mybatis.Page;
import io.github.talelin.latticy.dto.BannerDTO;
import io.github.talelin.latticy.mapper.BannerMapper;
import io.github.talelin.latticy.model.BannerDO;
import io.github.talelin.latticy.service.BannerService;
import io.github.talelin.latticy.vo.PageResponseVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class BannerServiceImpl implements BannerService {
@Autowired
private BannerMapper bannerMapper;
public void update(BannerDTO dto, Integer id){
BannerDO bannerDO = bannerMapper.selectById(id);
if (bannerDO == null) {
throw new NotFoundException(20000);
}
/*
* org.springframework.beans.BeanUtils
* 把dto拷贝到bannerDo中
* */
BeanUtils.copyProperties(dto, bannerDO);
bannerMapper.updateById(bannerDO);
}
public PageResponseVO<BannerDO> getBanners(Integer page,Integer count){
Page<BannerDO> pager = new Page<>(page,count);
IPage<BannerDO> paging = bannerMapper.selectPage(pager, null);
return new PageResponseVO<BannerDO>((int)paging.getTotal(), paging.getRecords(), (int)paging.getCurrent(), (int)paging.getSize());
}
}
3.4、创建UnifyResponseVO
package io.github.talelin.latticy.vo;
import io.github.talelin.autoconfigure.bean.Code;
import io.github.talelin.autoconfigure.util.RequestUtil;
import io.github.talelin.latticy.common.util.ResponseUtil;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import org.springframework.http.HttpStatus;
/**
* 统一API响应结果封装
*
* @author pedro@TaleLin
* @author colorful@TaleLin
* @author Juzi@TaleLin
*/
@Data
@Builder
@AllArgsConstructor
public class UnifyResponseVO<T> {
private Integer code;
private T message;
private String request;
public UnifyResponseVO() {
this.code = Code.SUCCESS.getCode();
this.request = RequestUtil.getSimpleRequest();
}
public UnifyResponseVO(int code) {
this.code = code;
this.request = RequestUtil.getSimpleRequest();
}
public UnifyResponseVO(T message) {
this.code = Code.SUCCESS.getCode();
this.message = message;
this.request = RequestUtil.getSimpleRequest();
}
public UnifyResponseVO(int code, T message) {
this.code = code;
this.message = message;
this.request = RequestUtil.getSimpleRequest();
}
public UnifyResponseVO(T message, HttpStatus httpStatus) {
this.code = Code.SUCCESS.getCode();
this.message = message;
this.request = RequestUtil.getSimpleRequest();
ResponseUtil.setCurrentResponseHttpStatus(httpStatus.value());
}
public UnifyResponseVO(int code, T message, HttpStatus httpStatus) {
this.code = code;
this.message = message;
this.request = RequestUtil.getSimpleRequest();
ResponseUtil.setCurrentResponseHttpStatus(httpStatus.value());
}
}
3.4.1创建UpdatedVO
package io.github.talelin.latticy.vo;
import io.github.talelin.autoconfigure.bean.Code;
import io.github.talelin.latticy.common.util.ResponseUtil;
import org.springframework.http.HttpStatus;
/**
* @author pedro@TaleLin
*/
public class UpdatedVO extends UnifyResponseVO<String> {
public UpdatedVO() {
super(Code.UPDATED.getCode());
ResponseUtil.setCurrentResponseHttpStatus(HttpStatus.CREATED.value());
}
public UpdatedVO(int code) {
super(code);
ResponseUtil.setCurrentResponseHttpStatus(HttpStatus.CREATED.value());
}
public UpdatedVO(String message) {
super(message);
ResponseUtil.setCurrentResponseHttpStatus(HttpStatus.CREATED.value());
}
public UpdatedVO(int code, String message) {
super(code, message);
ResponseUtil.setCurrentResponseHttpStatus(HttpStatus.CREATED.value());
}
@Override
public String toString() {
return super.toString();
}
}
3.4.2创建DeletedVO
package io.github.talelin.latticy.vo;
import io.github.talelin.autoconfigure.bean.Code;
import io.github.talelin.latticy.common.util.ResponseUtil;
import org.springframework.http.HttpStatus;
/**
* @author colorful@TaleLin
*/
public class DeletedVO extends UnifyResponseVO<String> {
public DeletedVO() {
super(Code.DELETED.getCode());
ResponseUtil.setCurrentResponseHttpStatus(HttpStatus.CREATED.value());
}
public DeletedVO(int code) {
super(code);
ResponseUtil.setCurrentResponseHttpStatus(HttpStatus.CREATED.value());
}
public DeletedVO(String message) {
super(message);
ResponseUtil.setCurrentResponseHttpStatus(HttpStatus.CREATED.value());
}
public DeletedVO(int code, String message) {
super(code, message);
ResponseUtil.setCurrentResponseHttpStatus(HttpStatus.CREATED.value());
}
@Override
public String toString() {
return super.toString();
}
}
3.4.3创建CreatedVO
package io.github.talelin.latticy.vo;
import io.github.talelin.autoconfigure.bean.Code;
import io.github.talelin.latticy.common.util.ResponseUtil;
import org.springframework.http.HttpStatus;
/**
* @author colorful@TaleLin
*/
public class CreatedVO extends UnifyResponseVO<String> {
public CreatedVO() {
super(Code.CREATED.getCode());
ResponseUtil.setCurrentResponseHttpStatus(HttpStatus.CREATED.value());
}
public CreatedVO(int code) {
super(code);
ResponseUtil.setCurrentResponseHttpStatus(HttpStatus.CREATED.value());
}
public CreatedVO(String message) {
super(message);
ResponseUtil.setCurrentResponseHttpStatus(HttpStatus.CREATED.value());
}
public CreatedVO(int code, String message) {
super(code, message);
ResponseUtil.setCurrentResponseHttpStatus(HttpStatus.CREATED.value());
}
@Override
public String toString() {
return super.toString();
}
}
3.5创建Controller
package io.github.talelin.latticy.controller.v1;
import io.github.talelin.core.annotation.GroupRequired;
import io.github.talelin.core.annotation.PermissionMeta;
import io.github.talelin.latticy.dto.BannerDTO;
import io.github.talelin.latticy.model.BannerDO;
import io.github.talelin.latticy.service.BannerService;
import io.github.talelin.latticy.vo.PageResponseVO;
import io.github.talelin.latticy.vo.UpdatedVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.Positive;
@RequestMapping("/v1/banner")
@RestController
@Validated
public class BannerController {
@Autowired
private BannerService bannerService;
@PutMapping("/updateBanner/{id}")
public UpdatedVO update(@RequestBody @Validated BannerDTO dto,
@PathVariable @Positive Integer id) {
bannerService.update(dto, id);
return new UpdatedVO();
}
@GetMapping("/page")
public PageResponseVO<BannerDO> getBanners(
@RequestParam(required = false, defaultValue = "0")
@Min(value = 0) Integer page,
@RequestParam(required = false, defaultValue = "10")
@Min(value = 1) @Max(value = 30) Integer count
){
return bannerService.getBanners(page,count);
}
}
3.6创建BannerDTO
package io.github.talelin.latticy.dto;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.validator.constraints.Length;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.List;
@Getter
@Setter
public class BannerDTO {
@NotBlank
@Length(min = 2, max = 20)
private String name;
@Length(min = 2, max = 30)
private String title;
private Integer version;
@Length(min = 2, max = 256)
private String img;
@Length(min = 2, max = 256)
private String description;
@NotNull
private List<BannerItemDTO> bannerItems;
}
四、创建删除方法
删除分:逻辑删除和物理删除。下面开始讲解逻辑删除
4.1逻辑删除
4.4.1修改BannerVO
需要在model增加注解@TableLogic
package io.github.talelin.latticy.model;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Getter;
import lombok.Setter;
import java.util.Date;
@Getter
@Setter
@TableName("banner")
public class BannerDO {
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
private String name;
private String title;
private String description;
private String img;
@JsonIgnore
private Date createTime;
@JsonIgnore
private Date updateTime;
/* @TableLogic注解参数
value = "" 默认的原值
delval = "" 删除后的值
@TableLogic(value="原值",delval="改值")
* */
@JsonIgnore
@TableLogic
private Date deleteTime;
}
4.1.2修改BannerService接口
增加delete方法
package io.github.talelin.latticy.service;
import io.github.talelin.latticy.dto.BannerDTO;
import io.github.talelin.latticy.model.BannerDO;
import io.github.talelin.latticy.vo.PageResponseVO;
import io.github.talelin.latticy.vo.UpdatedVO;
public interface BannerService {
public PageResponseVO<BannerDO> getBanners(Integer page,Integer count);
public void update(BannerDTO dto, Integer id);
public void delete(Integer id);
}
4.1.3修改BannerServiceImpl接口
package io.github.talelin.latticy.service.impl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.github.talelin.autoconfigure.exception.NotFoundException;
import io.github.talelin.latticy.common.mybatis.Page;
import io.github.talelin.latticy.dto.BannerDTO;
import io.github.talelin.latticy.mapper.BannerMapper;
import io.github.talelin.latticy.model.BannerDO;
import io.github.talelin.latticy.service.BannerService;
import io.github.talelin.latticy.vo.PageResponseVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class BannerServiceImpl implements BannerService {
@Autowired
private BannerMapper bannerMapper;
public void delete(Integer id) {
BannerDO banner = bannerMapper.selectById(id);
if (banner == null) {
throw new NotFoundException(20000);
}
bannerMapper.deleteById(id);
}
public void update(BannerDTO dto, Integer id){
BannerDO bannerDO = bannerMapper.selectById(id);
if (bannerDO == null) {
throw new NotFoundException(20000);
}
/*
* org.springframework.beans.BeanUtils
* 把dto拷贝到bannerDo中
* */
BeanUtils.copyProperties(dto, bannerDO);
bannerMapper.updateById(bannerDO);
}
public PageResponseVO<BannerDO> getBanners(Integer page,Integer count){
Page<BannerDO> pager = new Page<>(page,count);
IPage<BannerDO> paging = bannerMapper.selectPage(pager, null);
return new PageResponseVO<BannerDO>((int)paging.getTotal(), paging.getRecords(), (int)paging.getCurrent(), (int)paging.getSize());
}
}
4.1.4创建BannerController的delete方法
package io.github.talelin.latticy.controller.v1;
import io.github.talelin.core.annotation.GroupRequired;
import io.github.talelin.core.annotation.PermissionMeta;
import io.github.talelin.latticy.dto.BannerDTO;
import io.github.talelin.latticy.model.BannerDO;
import io.github.talelin.latticy.service.BannerService;
import io.github.talelin.latticy.vo.DeletedVO;
import io.github.talelin.latticy.vo.PageResponseVO;
import io.github.talelin.latticy.vo.UpdatedVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import javax.validation.constraints.Positive;
@RequestMapping("/v1/banner")
@RestController
@Validated
public class BannerController {
@Autowired
private BannerService bannerService;
@DeleteMapping("/deleteBanner/{id}")
public DeletedVO delete(@PathVariable @Positive Integer id) {
bannerService.delete(id);
return new DeletedVO();
}
@PutMapping("/updateBanner/{id}")
public UpdatedVO update(@RequestBody @Validated BannerDTO dto,
@PathVariable @Positive Integer id) {
bannerService.update(dto, id);
return new UpdatedVO();
}
@GetMapping("/page")
public PageResponseVO<BannerDO> getBanners(
@RequestParam(required = false, defaultValue = "0")
@Min(value = 0) Integer page,
@RequestParam(required = false, defaultValue = "10")
@Min(value = 1) @Max(value = 30) Integer count
){
return bannerService.getBanners(page,count);
}
}
4.1.5查看List接口
结论:逻辑删除,数据库是存在的,只是增加了标识。
4.2、物理删除
4.2.1修改BannerBO
屏蔽@TableLogic
package io.github.talelin.latticy.model;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Getter;
import lombok.Setter;
import java.util.Date;
@Getter
@Setter
@TableName("banner")
public class BannerDO {
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
private String name;
private String title;
private String description;
private String img;
@JsonIgnore
private Date createTime;
@JsonIgnore
private Date updateTime;
/* @TableLogic注解参数
value = "" 默认的原值
delval = "" 删除后的值
@TableLogic(value="原值",delval="改值")
* */
@JsonIgnore
// @TableLogic
private Date deleteTime;
}