Mybatis使用Spring data Pageable的方法

引言

可能这个用法是个邪教了。。。但是简单说这都是历史缘故,貌似是项目最初用JPA后面还是换Mybatis了,我接手时候看着那个写好的Controller层觉得换了怪可惜的,就沿用了。网上找找,提供的方法都比较繁琐了,其实就几个依赖两行代码的事情,简单给出一下:

依赖

  1. 数据库的命名规范需要标准下划线命名。
  2. com.github.pagehelper.PageHelper
  3. com.google.common.base.CaseFormat

Maven

Spring data,Mybatis部分略,只给出这个工具类需要的引用

        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.2.3</version>
        </dependency>
        <!-- guava:驼峰/下划线格式互转 -->
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>28.0-jre</version>
        </dependency>

代码

import com.github.pagehelper.PageHelper;
import com.google.common.base.CaseFormat;
import org.springframework.data.domain.Pageable;

import java.util.stream.Collectors;

public class PageUtil {
    public static void startPage(Pageable pageable) {
        PageHelper.startPage(pageable.getPageNumber(), pageable.getPageSize()
                , pageable.getSort().stream().map(order -> CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, order.getProperty()) + " " + order.getDirection()).collect(Collectors.joining(",")));
    }
}

如果你不能用Java8,那按Java7的方法写就是了,多几行而已。

猜你喜欢

转载自www.cnblogs.com/cielosun/p/11222127.html
今日推荐