MybatisPlus的日常使用

news2024/10/10 10:52:42

一、基础接口

public interface BaseMapper<T> {

    /**
     * 插入一条记录
     * @param entity 实体对象
     */
    int insert(T entity);

    /**
     * 根据 ID 删除
     * @param id 主键ID
     */
    int deleteById(Serializable id);

    /**
     * 根据 columnMap 条件,删除记录
     * @param columnMap 表字段 map 对象
     */
    int deleteByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);

    /**
     * 根据 entity 条件,删除记录
     * @param queryWrapper 实体对象封装操作类(可以为 null)
     */
    int delete(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

    /**
     * 删除(根据ID 批量删除)
     * @param idList 主键ID列表(不能为 null 以及 empty)
     */
    int deleteBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);

    /**
     * 根据 ID 修改
     * @param entity 实体对象
     */
    int updateById(@Param(Constants.ENTITY) T entity);

    /**
     * 根据 whereEntity 条件,更新记录
     * @param entity        实体对象 (set 条件值,不能为 null)
     * @param updateWrapper 实体对象封装操作类(可以为 null,里面的 entity 用于生成 where 语句)
     */
    int update(@Param(Constants.ENTITY) T entity, @Param(Constants.WRAPPER) Wrapper<T> updateWrapper);

    /**
     * 根据 ID 查询
     * @param id 主键ID
     */
    T selectById(Serializable id);

    /**
     * 查询(根据ID 批量查询)
     * @param idList 主键ID列表(不能为 null 以及 empty)
     */
    List<T> selectBatchIds(@Param(Constants.COLLECTION) Collection<? extends Serializable> idList);

    /**
     * 查询(根据 columnMap 条件)
     * @param columnMap 表字段 map 对象
     */
    List<T> selectByMap(@Param(Constants.COLUMN_MAP) Map<String, Object> columnMap);

    /**
     * 根据 entity 条件,查询一条记录
     * @param queryWrapper 实体对象
     */
    T selectOne(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

    /**
     * 根据 Wrapper 条件,查询总记录数
     * @param queryWrapper 实体对象
     */
    Integer selectCount(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

    /**
     * 根据 entity 条件,查询全部记录
     * @param queryWrapper 实体对象封装操作类(可以为 null)
     */
    List<T> selectList(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

    /**
     * 根据 Wrapper 条件,查询全部记录
     * @param queryWrapper 实体对象封装操作类(可以为 null)
     */
    List<Map<String, Object>> selectMaps(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

    /**
     * 根据 Wrapper 条件,查询全部记录
     * 注意: 只返回第一个字段的值
     * @param queryWrapper 实体对象封装操作类(可以为 null)
     */
    List<Object> selectObjs(@Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

    /**
     * 根据 entity 条件,查询全部记录(并翻页)
     * @param page         分页查询条件(可以为 RowBounds.DEFAULT)
     * @param queryWrapper 实体对象封装操作类(可以为 null)
     */
    IPage<T> selectPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);

    /**
     * 根据 Wrapper 条件,查询全部记录(并翻页)
     * @param page         分页查询条件
     * @param queryWrapper 实体对象封装操作类
     */
    IPage<Map<String, Object>> selectMapsPage(IPage<T> page, @Param(Constants.WRAPPER) Wrapper<T> queryWrapper);
}

二、条件构造器Wrapper及语法

Wrapper:条件构造抽象类,最顶端父类
AbstractWrapper:用于查询条件封装,生成 sql 的 where 条件
    QueryWrapper:Entity 对象封装操作类,不是用 lambda 语法
    UpdateWrapper:Update 条件封装,用于 Entity 对象更新操作
    AbstractLambdaWrapper:Lambda 语法使用 Wrapper 统一处理解析 lambda 获取 column
        LambdaQueryWrapper:用于 Lambda 语法使用的查询 Wrapper
        LambdaUpdateWrapper:Lambda 更新封装 Wrapper

三、插件的使用

四、Dao层的组装及规范

1.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.Builder;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.Data;
import java.io.Serializable;
import java.util.Date;
import java.math.BigDecimal;


@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
@TableName("customs")
public class Customs implements Serializable {

    private static final long serialVersionUID=1L;

    /**
     * id
     */
    @TableId(value = "id", type = IdType.AUTO)
    private String id;
	
    /**
     * 贸易方式
     */
    @TableField(value = "trade_way")
    private String tradeWay;

    /**
     * 报关发票号
     */
    @TableField(value = "report_invoice_no")
    private String reportInvoiceNo;

    /**
     * 唛头
     */
    @TableField(value = "mark_head")
    private String markHead;
	
    /**
     * 发票金额
     */
    @TableField(value = "invoice_amount")
    private BigDecimal invoiceAmount;
	
    /**
     * 状态(10草稿、20审批中、21审批通过、22驳回、30中止、40废弃)
     */
    @TableField(value = "status")
    private String status;

    /**
     * 是否删除 0 否 1 是
     */
    @TableField("del_flag")
    private Integer delFlag;
}

2.Dto

import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModelProperty;
import lombok.Builder;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.math.BigDecimal;
import java.util.List;

@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
public class CustomsDto {
	
    /**
     * id
     */
    @ApiModelProperty(value = "ID",example = "")
    private String id;

    /**
     * 清关单号
     */
    @ApiModelProperty(value = "清关单号",example = "")
    private String clearCustomsNo;

    /**
     * 报关单ID
     */
    @ApiModelProperty(value = "报关单ID",example = "")
    private String reportCustomsId;

    /**
     * 报关流水号
     */
    @ApiModelProperty(value = "报关流水号",example = "")
    @NotBlank(message = "报关流水号 不能为空", groups = { AddGroup.class, EditGroup.class })
    private String reportCustomsPipeNo;

    /**
     * 贸易方式
     */
    @ApiModelProperty(value = "贸易方式",example = "")
    private String tradeWay;


    /**
     * 币种
     */
    @ApiModelProperty(value = "币种",example = "")
    @NotBlank(message = "币种不能为空", groups = { AddGroup.class, EditGroup.class })
    private String currency;

    /**
     * 状态(10草稿、20审批中、21审批通过、22驳回、30中止、40废弃)
     */
    @ApiModelProperty(value = "状态(10草稿、20审批中、21审批通过、22驳回、30中止、40废弃)",example = "")
    private String status;

  
}

3. Mapper

import com.dao.entity.customs.clear.Customs;
import com.dto.customs.clear.CustomsDto;
import com.adp.commons.utils.mapper.BaseMapperPlus;


public interface CustomsMapper extends BaseMapperPlus<CustomsMapper, Customs, CustomsDto> {
}

4.Dao

import com.commons.group.beans.AuxResponse;
import com.commons.utils.AuxBeanUtil;
import com.commons.utils.AuxStringUtils;
import com.commons.utils.page.QueryBody;
import com.constants.CommonConst;
import com.constants.cumtoms.CumtomsConst;
import com.dao.entity.customs.clear.Customs;
import com.dao.mapper.customs.clear.CustomsMapper;
import com.dto.customs.clear.CustomsDto;
import com.enums.customs.CustomsNumberEnum;
import com.enums.customs.CustomsStatusEnum;
import com.query.customs.clear.CustomsParams;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;


@Slf4j
@Component
public class CustomsDao extends ServiceImpl<CustomsMapper,Customs> {

    @Autowired
    private CustomsMapper customsMapper;

    public String produceSerialNumber(){
        LambdaQueryWrapper<Customs> lqw = Wrappers.lambdaQuery();
        lqw.eq(Customs::getDelFlag, 1);
        lqw.orderByAsc(Customs::getCreateTime);
        CustomsDto clearCustomsDto =customsMapper.selectVoOne(lqw);
        if(clearCustomsDto==null){
            Customs clearCustoms = new Customs();
            clearCustoms.setDelFlag(1);
            customsMapper.insert(clearCustoms);
            return reportCustomsNo;
        }
        return sequenceService.generate(CustomsNumberEnum.REPORT_CUSTOMS_CLEAR_NO.code).getData();
    }


    /**
     * 通过ID 获取详情
     */
    public CustomsDto getInfoById(String id){
        CustomsDto dto = customsMapper.selectVoById(id);
        if(dto==null){
            return null;
        }
        ShippingCustomsClearAnnexsDto annexsDto = new ShippingCustomsClearAnnexsDto();
        annexsDto.setBusinessType(CommonConst.NUMBER_STR.TEN);
        annexsDto.setBusinessId(id);
        return dto;
    }

    /**
     * 分页查询
     */
    public Page<CustomsDto> queryPageList(QueryBody<CustomsParams> queryBody){
        LambdaQueryWrapper<Customs> lqw = buildQueryWrapper(queryBody.getParams());
        lqw.orderByDesc(Customs::getCreateTime);
        return customsMapper.selectVoPage(queryBody.getPageQuery().build(), lqw);
    }

    /**
     * 列表查询
     */
    public List<CustomsDto> queryList(CustomsParams params){
        LambdaQueryWrapper<Customs> lqw = buildQueryWrapper(params);
        lqw.orderByDesc(Customs::getCreateTime);
        List<CustomsDto> queryRet = customsMapper.selectVoList(lqw);
        Map<String,String> map = new HashMap<>();
        List<CustomsDto> ret = new ArrayList<>();
        for(CustomsDto clearCustomsDto : queryRet){
            String clearInvoiceNo = clearCustomsDto.getClearInvoiceNo();
            if(!map.containsKey(clearInvoiceNo)){
                ret.add(clearCustomsDto);
            }
            map.put(clearInvoiceNo,clearInvoiceNo);
        }
      return ret;
    }

    /**
     * 新增数据
     */
    public AuxResponse<String> add(CustomsDto dto){
        Customs add = AuxBeanUtil.copy(dto, Customs.class);
        String clearCustomsNo = add.getClearCustomsNo();
        if(clearCustomsNo==null||clearCustomsNo.isEmpty()){
            clearCustomsNo = sequenceService.generate(CustomsNumberEnum.REPORT_CUSTOMS_CLEAR_NO.code).getData();
        }
        // 判断是否已保存
        LambdaQueryWrapper<Customs> lqw = Wrappers.lambdaQuery();
        lqw.eq(Customs::getClearCustomsNo, clearCustomsNo);
        lqw.last(CommonConst.SQL_LIMIT);
        Customs getOneEntity = customsMapper.selectOne(lqw);
        if(getOneEntity!=null){
            return AuxResponse.FAILED(CumtomsConst.THIS_NO_HAVE_DATA);
        }
        add.setClearCustomsNo(clearCustomsNo);
        boolean flag = customsMapper.insert(add) > 0;
        String retId = add.getId();
        if (flag) {
            return AuxResponse.SUCCESS(retId);
        }
        return AuxResponse.FAILED(CommonConst.ERROR);
    }

    /**
     * 修改数据
     */
    public AuxResponse<String> update(CustomsDto dto){
        String id = dto.getId();
        Customs ret  = customsMapper.selectById(id);
        if(ret==null){
            return AuxResponse.FAILED(CumtomsConst.NOT_THIS_DATA);
        }
        String status = ret.getStatus();
        if(CustomsStatusEnum.DRAFT.code.equals(status)||CustomsStatusEnum.REJECTED.code.equals(status)||CustomsStatusEnum.APPROVAL_ING.code.equals(status)){
            try {
                if(CustomsStatusEnum.APPROVAL_ING.code.equals(status)){
                    Customs update = new Customs();
                    update.setId(dto.getId());
                    update.setAmountIsEqual(dto.getAmountIsEqual());
                    customsMapper.updateById(update);
                }else {
                    Customs update = AuxBeanUtil.copy(dto, Customs.class);
                    customsMapper.updateById(update);
                }
            }catch (Exception e){
                log.error("ShippingClearCustomsDao---update{}",e.getMessage());
                return AuxResponse.FAILED(e.getMessage());
            }
            return AuxResponse.SUCCESS(id);
        }
        return AuxResponse.FAILED(CumtomsConst.ONLY_OPERA_DRAFT_DATA);
    }

    /**
     * 取消
     */
    public String cancel(String id){
        try {
            Customs ret  = customsMapper.selectById(id);
            if(ret==null){
                return CumtomsConst.NOT_THIS_DATA;
            }
            String status =  ret.getStatus();
            if(CustomsStatusEnum.DRAFT.code.equals(status)||CustomsStatusEnum.REJECTED.code.equals(status)){
                ret = new Customs();
                ret.setId(id);
                ret.setStatus(CustomsStatusEnum.DISUSE.code);
                customsMapper.updateById(ret);
                return CommonConst.SUCCESS;
            }
            return CumtomsConst.ONLY_CANEL_DATA;
        }catch (Exception e){
            log.error("ShippingClearCustomsDao---cancel{}",e.getMessage());
        }
        return CommonConst.ERROR;
    }

    private LambdaQueryWrapper<Customs> buildQueryWrapper(CustomsParams params) {
        LambdaQueryWrapper<Customs> lqw = Wrappers.lambdaQuery();
        lqw.like(AuxStringUtils.isNotBlank(params.getClearCustomsNo()), Customs::getClearCustomsNo, params.getClearCustomsNo());
        lqw.eq(AuxStringUtils.isNotBlank(params.getReportCustomsPipeNo()), Customs::getReportCustomsPipeNo, params.getReportCustomsPipeNo());
        lqw.eq(AuxStringUtils.isNotBlank(params.getReportInvoiceNo()), Customs::getReportInvoiceNo, params.getReportInvoiceNo());
        lqw.like(AuxStringUtils.isNotBlank(params.getClearInvoiceNo()), Customs::getClearInvoiceNo, params.getClearInvoiceNo());
        lqw.like(AuxStringUtils.isNotBlank(params.getUnitName()), Customs::getUnitName, params.getUnitName());
        lqw.like(AuxStringUtils.isNotBlank(params.getCustomName()), Customs::getCustomName, params.getCustomName());
        lqw.eq(AuxStringUtils.isNotBlank(params.getStatus()), Customs::getStatus, params.getStatus());
        lqw.ne(AuxStringUtils.isNotBlank(params.getFromStatus()), Customs::getStatus, params.getFromStatus());
        return lqw;
    }

}

五、常用注解

<!--mybatis-plus-->
<dependency>
	<groupId>com.baomidou</groupId>
	<artifactId>mybatis-plus-boot-starter</artifactId>
	<version>3.0.5</version>
</dependency>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2201799.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Anthropic Message Batches API 满足批量处理大量请求

现在开发的系统有大量知识汇总统计、跑批处理需求的同学可以尝试一下&#xff0c;看看能不能解决自己目前的问题~~ 可能是一个解决方案 Anthropic 推出的 Message Batches API &#xff0c;专门用于帮助开发者批量处理大量请求。它的主要目的是通过一次性处理大量非实时任务&a…

Linux工具的使用——【gcc/g++的使用】【make/Makefile的使用】【如何让普通用户使用sudo】

目录 Linux工具的使用-021.如何让普通用户使用sudo1.1为什么无法使用sudo1.2解决步骤1.3验证 2.编译器gcc/g的使用2.1预处理2.2编译2.3汇编2.4链接2.5函数库2.5.1静态库与动态库2.5.1.1动态链接2.5.1.2静态链接 2.6gcc的默认链接方式2.7gcc的静态链接2.8g的使用2.8.1g的静态链接…

Apache Flink Dashboard

1、Overview Apache Flink Web Dashboardhttp://110.40.130.231:8081/#/overview 这张图片显示的是Apache Flink的Web UI界面&#xff0c;其中包含了以下几个部分&#xff1a; Available Task Slots: 显示当前可用的任务槽位数量。任务槽位是指Flink集群中可用于运行任务的资…

【华为HCIP实战课程十】OSPF网络DR和BDR实战讲解,网络工程师

一、DR与BDR的基础介绍 点到点同步LSA成本小 多点接入网络同步LSA成本大,需要DR/BDR 由于MA网络中,任意两台路由器都需要传递路由信息,网络中有n台路由器,则需要建立n*(n-1)/2个邻接关系。任何一台路由器的路由变化都会导致多次传递,浪费了带宽资源,DR和BDR应运而生!…

大数据存储计算平台EasyMR:多集群统一管理助力企业高效运维

随着全球企业进入数字化转型的快车道&#xff0c;数据已成为企业运营、决策和增长的核心驱动力。为了处理海量数据&#xff0c;同时应对数据处理的复杂性和确保系统的高可用性&#xff0c;企业往往选择部署多个Hadoop集群&#xff0c;这样的策略可以将生产环境、测试环境和灾备…

分布式 ID

背景 在复杂分布式系统中&#xff0c;往往需要对大量的数据和消息进行唯一标识。随着数据日渐增长&#xff0c;对数据分库分表后也需要有一个唯一ID来标识一条数据或消息&#xff0c;数据库的自增 ID 显然不能满足需求&#xff1b;此时一个能够生成全局唯一 ID 的系统是非常必…

电商选品/跟卖| 亚马逊卖家精灵爬虫

卖家精灵(SellerSprite)基于大数据和人工智能技术,精准查询每个产品的销量、关键词、自然搜索数据,为亚马逊跨境卖家提供一站式选品、市场分析、关键词优化、产品监控等, 基于买家精灵跟卖,可谓事半功倍, 如何利用买家精灵, 快速获取跟卖信息. from extensions.basic_exte…

Java基础知识——String篇

一、String 1、是什么 String 是 Java 中用于表示字符串的类。Java 中的字符串是不可变的&#xff0c;也就是说一旦创建&#xff0c;字符串的内容无法更改。 2、如何构造 &#xff08;1&#xff09;无参数构造方法&#xff1a; String str new String(); //创建一个空字符…

毕业设计项目-基于Spring Boot开发的古诗词管理系统

项目简介 这是一个基于Spring Boot开发的古诗词管理系统&#xff0c;旨在为用户提供在线古诗词交流平台。系统分为用户和管理员两个角色&#xff0c;各自拥有不同的功能和权限。该系统提供了以下功能&#xff1a; 用户功能&#xff1a; 登录和注册功能&#xff0c;确保用户身…

json格式的post请求目前不行, 要换成form表单形式的post请求怎么改

问: 下面是我的代码 export function fetchDeleteList<T>(agentSessionId: string) {return post<T>({url: http://192.168.0.116:8089/pipe-ics/agent/delete,method: post,data: { agentSessionId },}) } 目前是json格式的post请求, 目前不行, 要换成form表单…

如何使用IntelliJ IDEA生成UML图

&#x1f3dd;️ 博主介绍 大家好&#xff0c;我是一个搬砖的农民工&#xff0c;很高兴认识大家 &#x1f60a; ~ &#x1f468;‍&#x1f393; 个人介绍&#xff1a;本人是一名后端Java开发工程师&#xff0c;坐标北京 ~ &#x1f389; 感谢关注 &#x1f4d6; 一起学习 &…

基于深度学习的花卉识别系统

简介&#xff1a; 基于Python的花卉识别分类系统利用深度学习和计算机视觉技术&#xff0c;能够准确识别和分类各种花卉&#xff0c;如玫瑰、郁金香和向日葵等。这种系统不仅有助于植物学研究和园艺管理&#xff0c;还在生态保护、智能农业和市场销售等领域展现广泛应用前景。随…

HAL库常用的函数:

目录 HAL库&#xff1a; 1.GPIO常用函数&#xff1a; 1.HAL_GPIO_ReadPin( ) 2.HAL_GPIO_WritePin( ) 3.HAL_GPIO_TogglePin( ) 4.HAL_GPIO_EXTI_IRQHandler( ) 5.HAL_GPIO_EXTI_Callback( ) 2.UART常用函数&#xff1a; 1.HAL_U…

使用ChatGPT高效撰写优质学术论文:从选题到完稿的全攻略指南

大家好,感谢关注。我是七哥,一个在高校里不务正业,折腾学术科研AI实操的学术人。关于使用ChatGPT等AI学术科研的相关问题可以和作者七哥(yida985)交流,多多交流,相互成就,共同进步,为大家带来最酷最有效的智能AI学术科研写作攻略。 本文将通过从选题到完稿,帮助学术科…

TypeScript 中接口的理解与应用场景

文章目录 一、接口的定义二、接口的使用1. 接口的基本定义2. 接口的应用示例3. 可选属性和只读属性4. 函数类型的属性5. 类型推断和索引签名6. 接口的继承 三、应用场景 一、接口的定义 接口在 TypeScript 中是一系列抽象方法的声明&#xff0c;它代表了一组方法的特征集合。这…

【10086网上营业厅-注册/登录安全分析报告】

前言 由于网站注册入口容易被黑客攻击&#xff0c;存在如下安全问题&#xff1a; 暴力破解密码&#xff0c;造成用户信息泄露短信盗刷的安全问题&#xff0c;影响业务及导致用户投诉带来经济损失&#xff0c;尤其是后付费客户&#xff0c;风险巨大&#xff0c;造成亏损无底洞…

win10家庭版ubantu子系统下载和配置anaconda3

打开anaconda官网的下载页Download Now | Anaconda 找到linux系统&#xff0c;选择这个x86的版本&#xff0c;右键它&#xff0c;选择《复制链接地址》 我现在复制出来的是https://repo.anaconda.com/archive/Anaconda3-2024.06-1-Linux-x86_64.sh 后续可能会有版本更新&…

ChatGPT完成论文润色的提示词分享

学境思源&#xff0c;一键生成论文初稿&#xff1a; AcademicIdeas - 学境思源AI论文写作 在论文写作的最后阶段&#xff0c;润色是确保文章质量的重要步骤。无论是语法检查、句式优化&#xff0c;还是提升语言的连贯性和一致性&#xff0c;润色都能显著提高论文的专业性与可读…

重学SpringBoot3-集成Redis(十一)之地理位置数据存储

更多SpringBoot3内容请关注我的专栏&#xff1a;《SpringBoot3》 期待您的点赞&#x1f44d;收藏⭐评论✍ 重学SpringBoot3-集成Redis&#xff08;十一&#xff09;之地理位置数据存储 1. GEO 命令简介2. 项目环境配置2.1. 依赖引入2.2. Redis 配置 3. GEO 数据存储和查询实现3…

C++ day04(友元 friend、运算符重载、String字符串)

目录 【1】友元 friend 1》概念 2》友元函数 3》友元类 4》友元成员函数 【2】运算符重载 1》概念 2》友元函数运算符重载 ​编辑 3》成员函数运算符重载 4》赋值运算符与类型转换运算符重载 5》注意事项 【3】String 字符串类 【1】友元 friend 1》概念 定义&#x…