How to play with the paging query of MyBatis-Plus

Table of Contents

1. What is MyBatis-Plus?

2. Precautions for paging query

3. Operation steps of paging query.

4. Ideas

1.domain

2.mapper

3.service

3.1 impl

4.controller

5. Test


1. What is MyBatis-Plus?

MyBatis-Plus (opens new window) (referred to as MP) is an enhancement tool for MyBatis (opens new window). Based on MyBatis, it only enhances without making changes. It is born to simplify development and improve efficiency.

Main features

  • Non-invasive: Only enhancements are made, no changes are made. Introducing it will not affect the existing project, and it is as smooth as silk
  • Low loss: Basic CURD will be automatically injected upon startup, with basically no loss in performance and direct object-oriented operation.
  • Powerful CRUD operations: Built-in universal Mapper and universal Service, most CRUD operations on a single table can be implemented with only a small amount of configuration, and there are also powerful conditional constructors to meet various usage needs
  • Support Lambda form invocation: Use Lambda expressions to conveniently write various query conditions, no longer need to worry about incorrectly written fields
  • Supports automatic generation of primary keys: Supports up to 4 primary key strategies (including distributed unique ID generator – Sequence), which can be freely configured to perfectly solve the primary key problem
  • Supports ActiveRecord mode: Supports ActiveRecord form calling. Entity classes only need to inherit the Model class to perform powerful CRUD operations.
  • Support custom global universal operations: Support global universal method injection (Write once, use anywhere)
  • Built-in code generator: Use code or Maven plug-ins to quickly generate Mapper, Model, Service, and Controller layer codes. It supports template engines and has many custom configurations waiting for you to use.
  • Built-in paging plug-in: Based on MyBatis physical paging, developers do not need to care about specific operations. After configuring the plug-in, writing paging is equivalent to ordinary List query
  • The paging plug-in supports multiple databases: supports MySQL, MariaDB, Oracle, DB2, H2, HSQL, SQLite, Postgre, SQLServer and other databases
  • Built-in performance analysis plug-in: It can output SQL statements and their execution time. It is recommended to enable this function during development and testing to quickly identify slow queries.
  • Built-in global interception plug-in: Provides intelligent analysis and blocking of delete and update operations in the entire table, and can also customize interception rules to prevent misoperations

2. Notes on paging query

In paging queries, we should pay attention to the paging parameters. For example:

pageSize, pageNum

pageNum indicates the current page, corresponding to the offset parameter of the limit statement. pageSize indicates the maximum number of pieces of data returned by this query statement, corresponding to the second parameter row_count of the limit statement.

These two parameters are necessary parameters, and other conditional filters are secondary parameters.

3. Operation steps of paging query.

1. Requirement: Message header delivery

2. Return format

4. Ideas

First of all, we know what the front-end parameters are and how they are passed. Then we know that this is a post request and we know what the interface path is. We can just define the interface name ourselves. And when observing the return format, we found that data from another table also needs to be returned, and it has a one-to-many relationship with the main table. So we use collections to receive and query by id. The specific operations are as follows

//mybatis-plus package

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>${mybatis-plus.version}</version>
</dependency>
<mybatis-plus.version>3.5.3.1</mybatis-plus.version>

1.domain

import lombok.Data;

@Data
public class ZjBidderListParam {
    private String address;
    private String bankNumber;
    private Long bidderId;
    private String dataStatus;
    private String depositBank;
    private String dutyNumber;
    private String location;
    private Long pageNum;
    private Long pageSize;
    private String phoneNumber;
    private String taskId;
    private String unitProperty;
    private String userName;
}
@Data
@TableName("zj_bidder")
public class ZjBidderDTO implements Serializable,Cloneable {
    /** Bidder ID */
    @TableId
    private Integer bidderId;
    /** Bidder name */
    private String userName ;
    /** area */
    private String location;
    /** Nature of the unit; government departments, state-owned enterprises, government platform companies, private enterprises, public institutions, social groups */
    private String unitProperty;
    /** Tax ID number */
    private String dutyNumber;
    /** Unit address */
    private String address;
    /** Phone number */
    private String phoneNumber;
    /** Account opening bank */
    private String depositBank ;
    /** Bank Account */
    private String bankNumber;
    /** Data status */
    private String dataStatus;
    /** Process processId */
    private String taskId;
    /** founder */
    private String createBy ;
    /** Creation time */
    private Date createTime;
    /** updater */
    private String updateBy ;
    /** Update time */
    private Date updateTime;

    /**Contact*/
    @TableField(exist = false)
    private List<ZjBidderContacterDTO> contacter;
}
@Data
@TableName("zj_bidder_contacter")
public class ZjBidderContacterDTO implements Serializable,Cloneable{
    /** Contact ID */
    @TableId
    private Integer contacterId;
    /** Contact name */
    private String userName ;
    /** telephone number */
    private String phoneNumber;
    /** Position */
    private String job;
    /** Bidder ID */
    private Integer bidderId;
    /** Data status */
    private String dataStatus;
    /** Process processId */
    private String taskId;
    /** founder */
    private String createBy ;
    /** Creation time */
    private Date createTime;
    /** updater */
    private String updateBy ;
    /** Update time */
    private Date updateTime;

    @Override
    public ZjBidderContacterDTO clone() {
        try {
            ZjBidderContacterDTO clone = (ZjBidderContacterDTO) super.clone();
            // TODO: copy mutable state here, so the clone can't change the internals of the original
            return clone;
        } catch (CloneNotSupportedException e) {
            throw new AssertionError();
        }
    }
}

2. mapper

/**
 * Annotations for BaseMapper MyBatis-Plus, which contain paging-related methods.
 */
public interface ZjBidderMapper extends BaseMapper<ZjBidderDTO> {
}
@Mapper
@Repository
public interface ZjBidderContacterMapper extends BaseMapper<ZjBidderContacterDTO> {
}

3. service

public interface ZjBidderService {
    TableDataInfo<ZjBidderDTO> getList(ZjBidderListParam param);
}
3.1 impl
@Service
@RequiredArgsConstructor
public class ZjBidderServiceImpl implements ZjBidderService {

    private final ZjBidderMapper zjBidderMapper;

    private final ZjBidderContacterMapper contacterMapper;

    @Override
    public TableDataInfo<ZjBidderDTO> getList(ZjBidderListParam param) {
        Page<ZjBidderDTO> page = new Page<>(param.getPageNum(),param.getPageSize());
        QueryWrapper<ZjBidderDTO> wrapper = new QueryWrapper<>();
        wrapper.eq("data_status",0)
                .eq(Objects.nonNull(param.getBidderId()),"bidder_id",param.getBidderId())
                .eq(StringUtils.isNotEmpty(param.getUserName()),"user_name",param.getUserName())
                .eq(StringUtils.isNotEmpty(param.getTaskId()),"TASK_ID",param.getTaskId())
                .eq(StringUtils.isNotEmpty(param.getLocation()),"location",param.getLocation())
                .eq(StringUtils.isNotEmpty(param.getUnitProperty()),"unit_property",param.getUnitProperty())
                .eq(StringUtils.isNotEmpty(param.getDutyNumber()),"duty_number",param.getDutyNumber())
                .eq(StringUtils.isNotEmpty(param.getAddress()),"address",param.getAddress())
                .eq(StringUtils.isNotEmpty(param.getPhoneNumber()),"phone_number",param.getPhoneNumber())
                .eq(StringUtils.isNotEmpty(param.getDepositBank()),"deposit_bank",param.getDepositBank())
                .eq(StringUtils.isNotEmpty(param.getBankNumber()),"bank_number",param.getBankNumber());
        Page<ZjBidderDTO> data = zjBidderMapper.selectPage(page, wrapper);
        for (ZjBidderDTO record : data.getRecords()) {
            QueryWrapper<ZjBidderContacterDTO> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("DATA_STATUS",0)
                    .eq("contacter_id",record.getBidderId());
            record.setContacter(contacterMapper.selectList(queryWrapper));
        }
        return TableDataInfo.build(data);
    }
}

4. controller

@RestController
@RequestMapping("/bidder")
@RequiredArgsConstructor
public class ZjBidderController {

    private final ZjBidderService bidderService;

    /**
     * List of bidders
     * @param param
     * @return
     */
    @PostMapping("/list")
    public TableDataInfo<ZjBidderDTO> getList(ZjBidderListParam param){
        return bidderService.getList(param);
    }
}
5. Test