Proficiency in Spring Boot - Chapter 12: Implementation of Paging Query Function

Keywords: Programming Java Spring github MySQL

This article will introduce how to implement paging query function, recommend using the page helper plug-in of github (in fact, you basically do this), but the implementation of this article is different in most ways, less nonsense, now take you to see where the difference is. First look at pom.xml dependencies: fairly simple mybatis-spring dependencies + mysql+pagehelper+fastjson

 <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.44</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!--pageHelper-->
        <!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper-spring-boot-starter -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.5</version>
        </dependency>
   
    </dependencies>

application.yml configuration

spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/javashop
    driver-class-name: com.mysql.jdbc.Driver
  http:
    encoding:
      charset: utf-8
      enabled: true
mybatis:
  type-aliases-package: com.developlee.mybatispagehelper.domain
  mapper-locations: classpath:/mapper/*.xml
pagehelper:
  helper-dialect: mysql
  reasonable: true
  support-methods-arguments: true
  params: count=countSql

Let's start with controller s. Let's go! Write a simpler one.

@RestController
public class UserController {

    @Autowired
    private UserServiceImpl userService;

    @PostMapping("/queryList")
    public ResponseEntity queryList(@RequestBody UserEntity userEntity) {
        List<UserEntity> userEntities = userService.findUserList(userEntity);
        return new ResponseEntity( new PageEntity<>(userEntities), HttpStatus.OK);
    }
}

Look carefully, did you find and no PageHelper.startPage(int num, int size)? Of course, there is no best, every page query to write this sentence, is it very annoying... And what is _PageEntity? Don't worry, let's unveil slowly. There's nothing to say about service and dao and userMapper.xml, just for userService.findList to find a list array normally. The code is too lazy to paste, occupy a position, I believe you will also. Next, that's the point. Look at what UserEntity entities do.

public class UserEntity extends BaseEntity {
    private Long id;
    private String username;
    private String password;
    private String mobile;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
}

OMG inherits a BaseEntity. What content does BaseEntity have? In fact, it's quite easy. It's some page parameters we want to pass.

public abstract class BaseEntity {

    //pagesize
    private Integer pageSize;
    //Paging Start
    private Integer pageNum;

    private Integer total;

    //Sort type DESC or AES
    private String sort;

    private String orderBy;

    @JSONField(serialize = false)
    public Integer getPageSize() {
        return pageSize;
    }


    public void setPageSize(Integer pageSize) {
        this.pageSize = pageSize;
    }

    @JSONField(serialize = false)
    public Integer getPageNum() {
        return pageNum;
    }


    public void setPageNum(Integer pageNum) {
        this.pageNum = pageNum;
    }

    @JSONField(serialize = false)
    public Integer getTotal() {
        return total;
    }

    public void setTotal(Integer total) {
        this.total = total;
    }

    @JSONField(serialize = false)
    public String getOrderBy() {
        return orderBy;
    }

    public void setOrderBy(String orderBy) {
        this.orderBy = orderBy;
    }

    @JSONField(serialize = false)
    public String getSort() {
        return sort;
    }

    public void setSort(String sort) {
        this.sort = sort;
    }
}

Note that none of these parameters need to be returned to the front end. So use @JSONField(serialize=false) to do it.

There seems to be nothing magical about this, uh, uh, yeah, it's all about passing parameters. Look at Page Entity. That's the protagonist today.


import com.github.pagehelper.Page;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;

/**
 * Page<E>results were packaged
 * <p/>
 * Multiple attributes for new paging
 */
@SuppressWarnings({"rawtypes", "unchecked"})
public class PageEntity<T> implements Serializable {
    private static final long serialVersionUID = 1L;
    //Current page
    private int currentPage;
    //Number of pages per page
    private int pageSize;
    //Total number of records
    private long total;
    //PageCount
    private int pages;
    //Result Set
    private List<T> list;
    //Is it page one?
    private boolean isFirstPage = false;
    //Is it the last page?
    private boolean isLastPage = false;


    public PageEntity() {
    }

    /**
     * Wrapping Page objects
     *
     * @param list
     */
    public PageEntity(List<T> list) {
        if (list instanceof Page) {
            Page page = (Page) list;
            this.currentPage = page.getPageNum();
            this.pageSize = page.getPageSize();

            this.pages = page.getPages();
            this.list = page;
            this.total = page.getTotal();
        } else if (list instanceof Collection) {
            this.currentPage = 1;
            this.pageSize = list.size();
            this.pages = 1;
            this.list = list;
            this.total = list.size();
        }
        if (list instanceof Collection) {
            //Judging page boundaries
            judgePageBoudary();
        }
    }

    /**
     * Determine page boundaries
     */
    private void judgePageBoudary() {
        isFirstPage = currentPage == 1;
        isLastPage = currentPage == pages;
    }

    public int getCurrentPage() {
        return currentPage;
    }

    public void setCurrentPage(int currentPage) {
        this.currentPage = currentPage;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public long getTotal() {
        return total;
    }

    public void setTotal(long total) {
        this.total = total;
    }

    public int getPages() {
        return pages;
    }

    public void setPages(int pages) {
        this.pages = pages;
    }

    public List<T> getList() {
        return list;
    }

    public void setList(List<T> List) {
        this.list = List;
    }

    public boolean isIsFirstPage() {
        return isFirstPage;
    }

    public void setIsFirstPage(boolean isFirstPage) {
        this.isFirstPage = isFirstPage;
    }

    public boolean isIsLastPage() {
        return isLastPage;
    }

    public void setIsLastPage(boolean isLastPage) {
        this.isLastPage = isLastPage;
    }

    @Override
    public String toString() {
        final StringBuffer sb = new StringBuffer("PageEntity{");
        sb.append("currentPage=").append(currentPage);
        sb.append(", pageSize=").append(pageSize);
        sb.append(", total=").append(total);
        sb.append(", pages=").append(pages);
        sb.append(", list=").append(list);
        sb.append(", isFirstPage=").append(isFirstPage);
        sb.append(", isLastPage=").append(isLastPage);
        sb.append(", navigatepageNums=");
        sb.append('}');
        return sb.toString();
    }
}

Watch Out! The Page Entiy (List < T > list) constructor further refines page Helper's Page. Look at page Helper's page class

public class Page<E> extends ArrayList<E> implements Closeable {
    private static final long serialVersionUID = 1L;
    private int pageNum;
    private int pageSize;
    private int startRow;
    private int endRow;
    private long total;
    private int pages;
    private boolean count;
    private Boolean reasonable;
    private Boolean pageSizeZero;
    private String countColumn;
    private String orderBy;
    private boolean orderByOnly;
    //It's unnecessary...
}

Just say no empty handles, postman tools test a wave to see. I wipe, what's the case, and say no to these page parameters, why is there in the list? Well, SpringBoot's default message format conversion, which is called messgeConvert, obviously we use fastjson. Natural MessageConvert also needs to be adapted to use fastjson. Implement WebMvcConfiguer interface in spring boot 2.0, and then override this method

/**
 * @author Lensen
 * @desc
 * @since 2018/8/25 21:45
 */
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
    //Message Format Conversion
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        //1. We need to define an object that convert s the message.
        FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
        //2. Add the configuration information of fastJson, such as: whether to format the returned json data;
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty,
                SerializerFeature.DisableCircularReferenceDetect,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteDateUseDateFormat);
        //3. Handling Chinese scrambling
        List<MediaType> fastMediaTypes = new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        //4. Add configuration information to convert.
        fastJsonHttpMessageConverter.setSupportedMediaTypes(fastMediaTypes);
        fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
        //5. Add convert to converters.
        converters.add(fastJsonHttpMessageConverter);
    }
}

Enable WebMvc Don't forget that forgetting won't work (I forgot from the beginning) In the test, get up Perfect ~I don't need to write PageHelper.startPage(int pageNum, int pageSize) in the code at all. I just focus on my logic. Save time and effort, spare time to spend more time with family and girlfriend. Bigo!

Finally, the above sample code is available in my github.com Find it in. My personal public number: the smart life of developlee. Focus on not necessarily update, update is not necessary.

Posted by smilley654 on Sun, 27 Jan 2019 21:48:15 -0800