引言
可能這個用法是個邪教了。。。但是簡單說這都是歷史緣故,貌似是項目最初用JPA后面還是換Mybatis了,我接手時候看着那個寫好的Controller層覺得換了怪可惜的,就沿用了。網上找找,提供的方法都比較繁瑣了,其實就幾個依賴兩行代碼的事情,簡單給出一下:
依賴
- 數據庫的命名規范需要標准下划線命名。
- com.github.pagehelper.PageHelper
- 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 Page startPage(Pageable pageable) {
return 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的方法寫就是了,多幾行而已。