MybatisPlus
1.0 基础代码
1.1 model.java
package com.gcb.platform.model.ad;
import com.alibaba.fastjson.annotation.JSONField;
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 com.gcb.platform.common.base.BaseEntity;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraints.Length;
import org.springframework.util.NumberUtils;
import javax.validation.constraints.NotBlank;
import java.util.Date;
/**
* <p>
* 资讯-文章表
* </p>
*
* @author lyl
* @since 2020-09-17
*/
@Data(staticConstructor = "create")
@EqualsAndHashCode(callSuper = true)
@Accessors(chain = true)
@TableName("ad_article")
@ApiModel(value = "Article对象", description = "资讯-文章表")
public class Article extends BaseEntity {
private static final long serialVersionUID = 1L;
@TableId(value = "id", type = IdType.INPUT)
@JSONField(serialize = false)
private Long id;
@Length(max = 128)
@NotBlank(message = "标题不能为空")
@ApiModelProperty(value = "标题")
private String title;
@Length(max = 128)
@NotBlank(message = "文章封面图片不能为空")
@ApiModelProperty(value = "文章封面图片")
private String cover;
@Length(max = 65535)
@NotBlank(message = "文章简介不能为空")
@ApiModelProperty(value = "文章简介")
private String introduction;
@Length(max = 65535)
@NotBlank(message = "内容不能为空")
@ApiModelProperty(value = "内容")
private String content;
@JSONField(format = "yyyy-MM-dd HH:mm")
@ApiModelProperty(value = "创建时间")
private Date creationTime;
@JSONField(format = "yyyy-MM-dd HH:mm")
@ApiModelProperty(value = "修改时间")
private Date updateTime;
@ApiModelProperty(value = "除数据库字段以为的所有字段放此对象里面")
@TableField(exist = false)
private Other other;
@ApiModelProperty("")
public String getStrId() {
return id == null ? null : id.toString();
}
public void setStrId(String strId) {
this.id = StringUtils.isBlank(strId) ? null : NumberUtils.parseNumber(strId, Long.class);
}
@Data
public static class Other {
// 除数据库字段以为的所有字段放此对象里面
}
}
1.2 Mapper.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="com.gcb.platform.repository.ad.ArticleMapper">
</mapper>
1.3 Mapper.java
package com.gcb.platform.repository.ad;
import com.gcb.platform.model.ad.Article;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
/**
* <p>
* 资讯-文章表 Mapper 接口
* </p>
*
* @author lyl
* @since 2020-09-17
*/
public interface ArticleMapper extends BaseMapper<Article> {
}
1.4 Service.java
package com.gcb.platform.service.ad;
import com.gcb.platform.model.ad.Article;
import com.baomidou.mybatisplus.extension.service.IService;
/**
* <p>
* 资讯-文章表 服务类
* </p>
*
* @author lyl
* @since 2020-09-17
*/
public interface ArticleService extends IService<Article> {
}
1.5 ServiceImpl.java
package com.gcb.platform.service.ad.impl;
import com.gcb.platform.model.ad.Article;
import com.gcb.platform.repository.ad.ArticleMapper;
import com.gcb.platform.service.ad.ArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
/**
* <p>
* 资讯-文章表 服务实现类
* </p>
*
* @author lyl
* @since 2020-09-17
*/
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {
}
1.6 ArticleController.java
package com.gcb.platform.controller.ad.manage;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.gcb.platform.common.base.BaseController;
import com.gcb.platform.model.ad.Article;
import com.gcb.platform.service.ad.ArticleService;
import com.gcb.platform.utils.idgen.IdGenUtil;
import com.gcb.platform.utils.log.HotelLog;
import com.gcb.platform.utils.page.IPageInfo;
import com.gcb.platform.utils.response.AjaxRes;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.Date;
/**
* <p>
* 资讯-文章表 前端控制器
* </p>
*
* @author lyl
* @since 2020-09-17
*/
@Slf4j
@SuppressWarnings("unchecked")
@Api(tags = "资讯-文章表 - 后台")
@RestController
@RequestMapping(value = "/manage/pf/article")
public class ArticleController extends BaseController<Article> {
@Resource
private ArticleService articleService;
/**
* 获取分页数据
*
* @param currentPage 当前页码
* @param pageSize 当前页记录数
* @return 分页记录数
*/
@GetMapping
@RequiresPermissions("manage:article:list")
@ApiOperation("获取分页数据")
public AjaxRes<IPageInfo<Article>> page(
@RequestParam(value = "pageNum", defaultValue = "1")
@ApiParam("页码,默认第1页") long currentPage,
@RequestParam(value = "pageSize", defaultValue = "15")
@ApiParam("每页记录数,默认15条") long pageSize,
@RequestParam(value = "keyWord", required = false)
@ApiParam("查询关键字") String keyWord,
@RequestParam(value = "startTime", required = false)
@ApiParam("开始时间") String startTime,
@RequestParam(value = "endTime", required = false)
@ApiParam("结束时间") String endTime) {
AjaxRes<IPageInfo<Article>> res = new AjaxRes<>();
IPageInfo<Article> page = new IPageInfo<>(currentPage, pageSize);
LambdaQueryWrapper<Article> queryWrapper = Wrappers.lambdaQuery();
queryWrapper.select(Article::getId, Article::getIntroduction,
Article::getCreationTime, Article::getTitle)
.and(StringUtils.isNotEmpty(keyWord),
wrappers -> wrappers.like(StringUtils.isNotEmpty(keyWord),
Article::getTitle, keyWord)
.or().like(StringUtils.isNotEmpty(keyWord),
Article::getIntroduction, keyWord))
.between(StringUtils.isNotEmpty(startTime) && StringUtils.isNotEmpty(endTime),
Article::getCreationTime, startTime, endTime)
.orderByDesc(Article::getId);
articleService.page(page, queryWrapper);
res.succeed(page);
return res;
}
/**
* 根据 ID 获取数据
*
* @param id 记录 ID
* @return 该ID的单条数据
*/
@GetMapping("/{id}")
@RequiresPermissions("manage:article:get")
@ApiOperation("根据 ID 获取数据")
public AjaxRes<Article> get(@PathVariable("id") @ApiParam("数据ID") Long id) {
AjaxRes<Article> res = new AjaxRes<>();
LambdaQueryWrapper<Article> queryWrapper = Wrappers.<Article>lambdaQuery()
.eq(Article::getId, id);
queryWrapper.select(Article::getId, Article::getContent,
Article::getIntroduction, Article::getCover, Article::getTitle);
Article article = articleService.getOne(queryWrapper);
res.succeed(article);
return res;
}
/**
* 保存数据
*
* @param article 需要保存的数据对象
* @return 原样返回数据对象
*/
@PostMapping
@HotelLog("资讯-文章表 - 保存")
@RequiresPermissions("manage:article:save")
@ApiOperation("保存数据")
public AjaxRes<Article> save(@RequestBody @Validated Article article, BindingResult br) {
AjaxRes<Article> res = before(br);
if (ObjectUtil.isNotNull(res)) {
return res;
}
res = new AjaxRes<>();
article.setId(IdGenUtil.uniqueId());
if (articleService.save(article)) {
res.succeed();
}
return res;
}
/**
* 根据 ID 更新数据
*
* @param article 需要更新的数据对象
* @return 原样返回数据对象
*/
@PutMapping
@HotelLog("资讯-文章表 - 更新")
@RequiresPermissions("manage:article:update")
@ApiOperation("根据 ID 更新数据")
public AjaxRes<Article> updateById(@RequestBody @Validated Article article,
BindingResult br) {
AjaxRes<Article> res = before(br);
if (ObjectUtil.isNotNull(res)) {
return res;
}
res = new AjaxRes<>();
article.setUpdateTime(new Date());
if (articleService.updateById(article)) {
res.succeed();
}
return res;
}
/**
* 根据 ID 删除数据
*
* @param id 数据 ID
* @return 删除成功返回true, 反之,返回false
*/
@DeleteMapping("/{id}")
@HotelLog("资讯-文章表 - 删除")
@RequiresPermissions("manage:article:delete")
@ApiOperation("根据 ID 删除数据")
public AjaxRes<Boolean> removeById(@PathVariable("id") @ApiParam("数据ID") Long id) {
AjaxRes<Boolean> res = new AjaxRes<>();
if (articleService.removeById(id)) {
res.succeed(true);
}
return res;
}
}
2.0 查询单个
select id ,title from ad_article where id = id
常用写法
public void getOne(Long id){
LambdaQueryWrapper<Article> queryWrapper = Wrappers.<Article>lambdaQuery()
.eq(Article::getId, id);
queryWrapper.select(Article::getId, Article::getTitle);
Article article = articleService.getOne(queryWrapper);
}
public void getOne(Long id){
Article article = articleService.lambdaQuery().eq(Article::getId, id)
.select(Article::getId, Article::getTitle).one();
}
// 根据 ID 查询
T getById(Serializable id);
// 根据 Wrapper,查询一条记录。结果集,如果是多个会抛出异常,随机取一条加上限制条件 wrapper.last("LIMIT 1")
T getOne(Wrapper<T> queryWrapper);
// 根据 Wrapper,查询一条记录
T getOne(Wrapper<T> queryWrapper, boolean throwEx);
// 根据 Wrapper,查询一条记录
Map<String, Object> getMap(Wrapper<T> queryWrapper);
// 根据 Wrapper,查询一条记录
<V> V getObj(Wrapper<T> queryWrapper, Function<? super Object, V> mapper);
3.0 查询多个
select id , title from ad_article where title like '%keyWord%' order by id desc
常用写法
public void getList(String keyWord){
LambdaQueryWrapper<Article> queryWrapper = Wrappers.<Article>lambdaQuery()
.select(Article::getId, Article::getTitle)
.like(StringUtils.isNotEmpty(keyWord), Article::getTitle, keyWord)
.orderByDesc(Article::getId);
List<Article> list = articleService.list(queryWrapper);
}
public void getList(String keyWord){
List<Article> list = articleService.lambdaQuery()
.like(StringUtils.isNotEmpty(keyWord), Article::getTitle, keyWord)
.select(Article::getId, Article::getTitle)
.orderByDesc(Article::getId)
.list();
}
// 查询所有
List<T> list();
// 查询列表
List<T> list(Wrapper<T> queryWrapper);
// 查询(根据ID 批量查询)
Collection<T> listByIds(Collection<? extends Serializable> idList);
// 查询(根据 columnMap 条件)
Collection<T> listByMap(Map<String, Object> columnMap);
// 查询所有列表
List<Map<String, Object>> listMaps();
// 查询列表
List<Map<String, Object>> listMaps(Wrapper<T> queryWrapper);
// 查询全部记录
List<Object> listObjs();
// 查询全部记录
<V> List<V> listObjs(Function<? super Object, V> mapper);
// 根据 Wrapper 条件,查询全部记录
List<Object> listObjs(Wrapper<T> queryWrapper);
// 根据 Wrapper 条件,查询全部记录
<V> List<V> listObjs(Wrapper<T> queryWrapper, Function<? super Object, V> mapper);
4.0 分页查询
select id , title from ad_article title like '%keyWord%'
limit ((currentPage - 1) * pageSize) , pageSize
常用写法
public void page(long currentPage, long pageSize, String keyWord){
IPageInfo<Article> page = new IPageInfo<>(currentPage, pageSize);
LambdaQueryWrapper<Article> queryWrapper = Wrappers.lambdaQuery();
queryWrapper.select(Article::getId, Article::getTitle)
.like(StringUtils.isNotEmpty(keyWord), Article::getTitle, keyWord)
.orderByDesc(Article::getId);
articleService.page(page, queryWrapper);
}
public void page(long currentPage, long pageSize, String keyWord){
IPageInfo<Article> page = new IPageInfo<>(currentPage, pageSize);
articleService.lambdaQuery().select(Article::getId, Article::getTitle)
.like(StringUtils.isNotEmpty(keyWord), Article::getTitle, keyWord)
.page(page);
}
// 无条件分页查询
IPage<T> page(IPage<T> page);
// 条件分页查询
IPage<T> page(IPage<T> page, Wrapper<T> queryWrapper);
// 无条件分页查询
IPage<Map<String, Object>> pageMaps(IPage<T> page);
// 条件分页查询
IPage<Map<String, Object>> pageMaps(IPage<T> page, Wrapper<T> queryWrapper);
package com.gcb.platform.utils.page;
import com.alibaba.fastjson.annotation.JSONField;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import java.util.List;
/**
* 分页对象,兼容旧系统而立
*
* @param <T>
*/
@ApiModel
public class IPageInfo<T> extends Page<T> {
private static final long serialVersionUID = 8091940070756181147L;
public IPageInfo() {
}
public IPageInfo(long current, long size) {
super(current, size);
}
public IPageInfo(long current, long size, long total) {
super(current, size, total);
}
public IPageInfo(long current, long size, boolean isSearchCount) {
super(current, size, isSearchCount);
}
public IPageInfo(long current, long size, long total, boolean isSearchCount) {
super(current, size, total, isSearchCount);
}
@ApiModelProperty("其它数据")
private Object other;
@ApiModelProperty("当前页码")
public long getPageNum() {
return getCurrent();
}
@ApiModelProperty("每页纪录数")
public long getPageSize() {
return getSize();
}
public List<T> getList() {
return getRecords();
}
public void setList(List<T> list) {
super.setRecords(list);
}
@Override
@JSONField(serialize = false)
@ApiModelProperty(hidden = true)
public List<T> getRecords() {
return super.getRecords();
}
@Override
@JSONField(serialize = false)
@ApiModelProperty(hidden = true)
public long getSize() {
return super.getSize();
}
@Override
@JSONField(serialize = false)
@ApiModelProperty(hidden = true)
public long getCurrent() {
return super.getCurrent();
}
@Override
@JSONField(serialize = false)
@ApiModelProperty(hidden = true)
public boolean isSearchCount() {
return super.isSearchCount();
}
public Object getOther() {
return other;
}
public void setOther(Object other) {
this.other = other;
}
}
5.0 删除单个
delete from ad_article where id = id;
常用写法
public void deleteOne(long id){
LambdaQueryWrapper<Article> wrapper = Wrappers.<Article>lambdaQuery()
.eq(Article::getId, id);
articleService.remove(wrapper);
}
public void deleteOne(long id){
articleService.removeById(id)
}
// 根据 ID 删除
boolean removeById(Serializable id);
6.0 删除多个
delete from ad_article where id > 1
常用写法
public void delete(long id){
LambdaQueryWrapper<Article> wrapper = Wrappers.<Article>lambdaQuery()
.gt(Article::getId, id);
articleService.remove(wrapper);
}
// 根据 entity 条件,删除记录
boolean remove(Wrapper<T> queryWrapper);
// 根据 columnMap 条件,删除记录
boolean removeByMap(Map<String, Object> columnMap);
// 删除(根据ID 批量删除)
boolean removeByIds(Collection<? extends Serializable> idList);
7.0 更新数据
// 根据 UpdateWrapper 条件,更新记录 需要设置sqlset
boolean update(Wrapper<T> updateWrapper);
// 根据 whereEntity 条件,更新记录
boolean update(T entity, Wrapper<T> updateWrapper);
// 根据 ID 选择修改
boolean updateById(T entity);
// 根据ID 批量更新
boolean updateBatchById(Collection<T> entityList);
// 根据ID 批量更新
boolean updateBatchById(Collection<T> entityList, int batchSize);
8.0 更新字段为 NULL
-
原因:mybatis-plus会将所有为空的字段在修改时进行过滤,不进行设为空的修改操作。
-
解决办法1:@TableField(strategy = FieldStrategy.IGNORED)
(不推荐有可能别人调用api的时候不希望更新null)
@TableField(strategy = FieldStrategy.IGNORED) private Long classId;
-
解决办法2: UpdateWrapper(推荐)
这里推荐一种方法,也是官网给出的,但是必须要求mp的版本 大于3,
如果是3以下的版本没有这个功能,就是使用UpdateWrapper.
public void update(){ LambdaUpdateWrapper<User> wrapper = new LambdaUpdateWrapper<>(); wrapper.set(User::getGender(), null); wrapper.eq(User::getId(), 1); userService.update(wrapper) }
9.0 保存单个
// 插入一条记录(选择字段,策略插入)
boolean save(T entity);
10.0 保存多个
// 插入(批量)
boolean saveBatch(Collection<T> entityList);
// 插入(批量)
boolean saveBatch(Collection<T> entityList, int batchSize);
11.0 保存或者更新
// TableId 注解存在更新记录,否插入一条记录
boolean saveOrUpdate(T entity);
// 根据updateWrapper尝试更新,否继续执行saveOrUpdate(T)方法
boolean saveOrUpdate(T entity, Wrapper<T> updateWrapper);
// 批量修改插入
boolean saveOrUpdateBatch(Collection<T> entityList);
// 批量修改插入
boolean saveOrUpdateBatch(Collection<T> entityList, int batchSize);
12.0 使用mybatisPlus 的 wrapper对象作为自定义sql的条件
<select id="listTaskMaps" resultType="map">
select
`status`,count(id) `count`
from (
select
id,status
from `h_task`
${ew.customSqlSegment}
union all
select
id,status
from `h_task_history`
${ew.customSqlSegment}
) h GROUP BY `status`
</select>
package com.gcb.platform.repository.platform;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.gcb.platform.model.platform.Publisher;
import com.gcb.platform.model.platform.Task;
import com.gcb.platform.utils.page.IPageInfo;
import org.apache.ibatis.annotations.Param;
import java.util.List;
import java.util.Map;
/**
* <p>
* 工单表 Mapper 接口
* </p>
*
* @author lyl
* @since 2020-06-30
*/
public interface ITaskMapper extends BaseMapper<Task> {
List<Map<String, Object>> listTaskMaps(@Param("ew") QueryWrapper<Task> query);
}
public void select(){
QueryWrapper<Task> query = Wrappers.<Task>query()
.in(CollectionUtils.isNotEmpty(taskIds), "id", taskIds)
.like(StringUtils.isNotBlank(taskCode), "task_code", taskCode)
.in(CollectionUtils.isNotEmpty(publisherIds), "publisher_id", publisherIds)
.in(CollectionUtils.isNotEmpty(eqIds), "equipment_id", eqIds)
.in(CollectionUtils.isNotEmpty(handleIds), "handle_id", handleIds)
.in(CollectionUtils.isNotEmpty(addressIds), "address_id", addressIds)
.eq(faultType != -1, "`fault_type`", faultType)
.eq(status != -1, "`status`", status)
.between("`creation_time`", startTime, endTime);
List<Map<String, Object>> counts = iTaskService.listTaskMaps(query);
}