SpringBoot case-employee management-pagination condition query

According to the page prototype, clarify the requirements

page prototype

need

 View interface documentation

Links to the interface documentation are as follows:

[Tencent Documents] Documents required for SpringBoot cases
https://docs.qq.com/doc/DUkRiTWVaUmFVck9N

Idea analysis

Pagination conditional query will display the results of conditional query in pages. Since some conditions may or may not be set, dynamic SQL statements are used to query, so the method of configuration file is adopted. For details, refer to the article: MyBatis-XML mapping file _Entropy 240 Blog-CSDN Blog

MyBatis-Dynamic SQL-if and where_Entropy 240 Blog-CSDN Blog

MyBatis-Dynamic SQL-foreach_Entropy 240 Blog-CSDN Blog

Interface function realization

Control layer (Controller class)

The specific key code is as follows

package com.example.tlias.controller;

import com.example.tlias.pojo.PageBean;
import com.example.tlias.pojo.Result;
import com.example.tlias.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;

@Slf4j
@RestController
public class EmpController {
    @Autowired
    private EmpService empService;

    @GetMapping("/emps")
    // 接收前端参数默认根据名称进行自动注入
    public Result page(@RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer pageSize,
                       String name,
                       // @RequestParam(required = false) 标表示该参数是可选的,不是必须传递的。
                       @RequestParam(required = false) Short gender,
                       @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin,
                       @DateTimeFormat LocalDate end) {
        // 设置未接受到参数值时,设置其默认值
        // if (page == null) page = 1;
        // if (pageSize == null) pageSize = 10;
        // todo 对gender地值进行判断
        log.info("分页查询,参数page:{}、pageSize:{},gender:{},name:{},begin:{},end:{}", page, pageSize, gender, name, begin, end);
        // 调用Service中的方法进行分页查询
        // 查询的结果封装到PageBean中
        PageBean pageBean = empService.Page(page, pageSize, name, gender, begin, end);
        return Result.success(pageBean);
    }
}

Business layer (Service class)

The specific key code is as follows

business class

package com.example.tlias.service;

import com.example.tlias.pojo.PageBean;
import org.springframework.format.annotation.DateTimeFormat;

import java.time.LocalDate;

public interface EmpService {
    PageBean Page(Integer page, Integer pageSize,
                  String name, Short gender,
                  @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDate begin,
                  @DateTimeFormat LocalDate end);
}

business realization class

    @Override
    public PageBean Page(Integer page, Integer pageSize, String name,
                         Short gender,
                         LocalDate begin, LocalDate end) {
        // 设置分页参数
        PageHelper.startPage(page, pageSize);
        // 执行正常查询操作
        List<Emp> empList = empMapper.list(name, gender, begin, end);
        Page<Emp> p = (Page<Emp>) empList;
        // 封装分页结果PageBean
        PageBean pageBean = new PageBean(p.getTotal(), p.getResult());
        return pageBean;
    }

Persistence layer (Mapper class)

The specific key codes are as follows:

package com.example.tlias.mapper;

import com.example.tlias.pojo.Emp;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

import java.time.LocalDate;
import java.util.List;

@Mapper
public interface EmpMapper {


    /**
     * 员工信息的查询
     * 使用pagehepler插件
     *
     * @return
     */
    public List<Emp> list(String name,
                          Short gender,
                          LocalDate begin,
                          LocalDate end);


}

Mapper.xml mapping file 

The specific key code is as follows

<?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.example.tlias.mapper.EmpMapper">
    <select id="list" resultType="com.example.tlias.pojo.Emp">
        select *
        from emp
        <where>
            <if test="name!=null">
                name like concat('%',#{name},'%')
            </if>
            <if test="gender!=null">
                and gender = #{gender}
            </if>
            <if test="begin!=null and end!=null">
                and entrydate between #{begin} and #{end}
            </if>
        </where>
        order by update_time desc
    </select>
</mapper>

In the above code, the data type of gender is Short , and the difference between the two data types of short and Short is as follows:

1. Data type: 
   - short is Java's primitive data type (primitive type), used to represent short integers (16-bit signed integers), ranging from -32,768 to 32,767. 
   - Short is a Java wrapper class (wrapper class), which encapsulates the short type and provides some additional functions, such as methods and attributes. 

2. Nullability: 
   - short is a primitive data type, it cannot be null. 
   - Short is a wrapper class which can be null. This allows us to use it in situations where we need to handle nulls, such as storing nulls in collections or representing missing values. 

3. Autoboxing and unboxing: 
   - short is a primitive data type, which does not support autoboxing and unboxing. If you need to assign a value of type short to a variable of type Short, or assign a value of type Short to a variable of type short, explicit type conversion is required. 
   - Short is a wrapper class which supports autoboxing and unboxing. This means that we can directly assign a value of type short to a variable of type Short, or assign a value of type Short to a variable of type short without explicit type conversion. 

4. Usage scenarios: 
   - short is usually used in scenarios that need to save memory space or have high performance requirements, such as in the case of massive data calculation or limited storage space. 
   -Short is usually used in scenarios that need to handle null or need to use special functions of wrapper classes (such as collection operations, reflection, etc.). 

To sum up, short is a primitive data type, suitable for simple numerical calculations and scenarios that save memory space; while Short is a wrapper class, suitable for scenarios that need to handle null or use special functions of wrapper classes.

interface test

After starting the SpringBoot project, use postman to test the interface function. The specific request address and request parameters are as follows:

There are also parameter values ​​that are not specified 

The result of the operation is as follows:

{
    "code": 1,
    "msg": "success",
    "data": {
        "total": 5,
        "rows": [
            {
                "id": 6,
                "username": "xiaozhao",
                "password": "123456",
                "name": "小昭",
                "gender": 2,
                "image": "6.jpg",
                "job": 3,
                "entrydate": "2013-09-05",
                "deptId": 1,
                "creteTime": null,
                "updateTime": "2023-08-07T15:44:50"
            },
            {
                "id": 7,
                "username": "jixiaofu",
                "password": "123456",
                "name": "纪晓芙",
                "gender": 2,
                "image": "7.jpg",
                "job": 1,
                "entrydate": "2005-08-01",
                "deptId": 1,
                "creteTime": null,
                "updateTime": "2023-08-07T15:44:50"
            },
            {
                "id": 8,
                "username": "zhouzhiruo",
                "password": "123456",
                "name": "周芷若",
                "gender": 2,
                "image": "8.jpg",
                "job": 1,
                "entrydate": "2014-11-09",
                "deptId": 1,
                "creteTime": null,
                "updateTime": "2023-08-07T15:44:50"
            }
        ]
    }
}

 

Front-end and back-end joint debugging

Open the nginx project provided by the course, the running results are as follows, and perform conditional pagination query

 

console output

 

run successfully 

 But read the output log carefully

When the front end does not pass the value of the name parameter, the SQL statement is still spliced ​​with the name query condition. According to the log content, the value of the name parameter is an empty string at this time, so the SQL statement must be improved. The specific changes are as follows:

 Add a judgment condition, run again and find that the problem has been solved

 

summary

  1. Conditional pagination query
    1. Conditional query: dynamic SQL-XML mapping file
    2. Paging query: PageHepler paging plugin in MyBatis

 

 

Guess you like

Origin blog.csdn.net/weixin_64939936/article/details/132327850