易筋SpringBoot 2.1 | 第廿二篇:SpringBoot的Mybatis分頁插件PageHelper

寫作時間:2019-09-10
Spring Boot: 2.1 ,JDK: 1.8, IDE: IntelliJ IDEA

說明

MyBatis PageHelper (https://pagehelper.github.io)

  • 支持多種數據庫
  • 支持多種分頁方式
  • SpringBoot 支持 (https://github.com/pagehelper/pagehelper-spring-boot)
    • pagehelper-spring-boot-starter

一般選擇用下面4中寫法

//第一種,RowBounds方式的調用
List<Country> list = sqlSession.selectList("x.y.selectIf", null, new RowBounds(0, 10));

//第二種,Mapper接口方式的調用,推薦這種使用方式。
PageHelper.startPage(1, 10);
List<Country> list = countryMapper.selectIf(1);

//第三種,Mapper接口方式的調用,推薦這種使用方式。
PageHelper.offsetPage(1, 10);
List<Country> list = countryMapper.selectIf(1);

//第四種,參數方法調用
//存在以下 Mapper 接口方法,你不需要在 xml 處理後兩個參數
public interface CountryMapper {
    List<Country> selectByPageNumSize(
            @Param("user") User user,
            @Param("pageNum") int pageNum,
            @Param("pageSize") int pageSize);
}
//配置supportMethodsArguments=true
//在代碼中直接調用:
List<Country> list = countryMapper.selectByPageNumSize(user, 1, 10);

工程建立

參照教程【SpringBoot 2.1 | 第一篇:構建第一個SpringBoot工程】新建一個Spring Boot項目,名字叫demodbmybatisgenerator, 在目錄src/main/java/resources 下找到配置文件application.properties,重命名爲application.yml

在Dependency中選擇
Developer Tools > Lombok
Web > Spring Web Starter
SQL > H2 DataBase / Mybatis Framework
Ops > Spring Boot Actuator。

在這裏插入圖片描述
pom.xml 修改mybatis的版本, 增加mybatis.pagehelper, joda


<dependencies>
	<dependency>
        <groupId>org.mybatis.spring.boot</groupId>
        <artifactId>mybatis-spring-boot-starter</artifactId>
        <version>1.3.2</version>
    </dependency>
    <dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper-spring-boot-starter</artifactId>
        <version>1.2.10</version>
    </dependency>
    <dependency>
        <groupId>org.joda</groupId>
        <artifactId>joda-money</artifactId>
        <version>LATEST</version>
    </dependency>
</dependencies>

Money類型轉換類

zgpeace.spring.data.handler.MoneyTypeHandler

package zgpeace.spring.data.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.joda.money.CurrencyUnit;
import org.joda.money.Money;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * exchange data type between Money and BigInt for 'CNY'
 */
public class MoneyTypeHandler extends BaseTypeHandler<Money> {
  @Override
  public void setNonNullParameter(PreparedStatement ps, int i, Money parameter, JdbcType jdbcType) throws SQLException {
    ps.setLong(i, parameter.getAmountMinorLong());
  }

  @Override
  public Money getNullableResult(ResultSet rs, String columnName) throws SQLException {
    return parseMoney(rs.getLong(columnName));
  }

  @Override
  public Money getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
    return parseMoney(rs.getLong(columnIndex));
  }

  @Override
  public Money getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
    return parseMoney(cs.getLong(columnIndex));
  }

  private Money parseMoney(Long value) {
    return Money.of(CurrencyUnit.of("CNY"), value / 100.0);
  }
}

application配置

src > main > resources > application.yml

mybatis:
  type-handlers-package: zgpeace.spring.data.handler
  configuration:
    map-underscore-to-camel-case: true
pagehelper:
  offset-as-page-num: true
  reasonable: true
  page-size-zero: true
  support-methods-arguments: true

創建表sql

Resources.schema.sql

create table t_coffee (
    id bigint not null auto_increment,
    name varchar(255),
    price bigint not null,
    create_time timestamp,
    update_time timestamp,
    primary key (id)
);

初始化數據

Resources.data.sql

insert into t_coffee (name, price, create_time, update_time) values ('espresso', 2000, now(), now());
insert into t_coffee (name, price, create_time, update_time) values ('latte', 2500, now(), now());
insert into t_coffee (name, price, create_time, update_time) values ('capuccino', 2500, now(), now());
insert into t_coffee (name, price, create_time, update_time) values ('mocha', 3000, now(), now());
insert into t_coffee (name, price, create_time, update_time) values ('macchiato', 3000, now(), now());

Model

zgpeace.spring.data.model.Coffee

package zgpeace.spring.data.model;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.joda.money.Money;

import java.util.Date;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Coffee {
  private Long id;
  private String name;
  private Money price;
  private Date createTime;
  private Date updateTime;
}

Mapper

zgpeace.spring.data.mapper.CoffeeMapper

package zgpeace.spring.data.mapper;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.session.RowBounds;
import zgpeace.spring.data.model.Coffee;

import java.util.List;

@Mapper
public interface CoffeeMapper {
  @Select("select * from t_coffee order by id")
  List<Coffee> findAllWithRowBounds(RowBounds rowBounds);

  @Select("select * from t_coffee order by id")
  List<Coffee> findAllWithParam(@Param("pageNum") int pageNum,
                                @Param("pageSize") int pageSize);
}

Controller 驗證分頁是否可用

zgpeace.spring.data.DemoDbMybatisPageHelperApplication

package zgpeace.spring.data;

import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.RowBounds;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import zgpeace.spring.data.mapper.CoffeeMapper;
import zgpeace.spring.data.model.Coffee;

import java.util.List;

@SpringBootApplication
@Slf4j
@MapperScan("zgpeace.spring.data.mapper")
public class DemoDbMybatisPageHelperApplication implements ApplicationRunner {
  @Autowired
  private CoffeeMapper coffeeMapper;

  public static void main(String[] args) {
    SpringApplication.run(DemoDbMybatisPageHelperApplication.class, args);
  }

  @Override
  public void run(ApplicationArguments args) throws Exception {
    coffeeMapper.findAllWithRowBounds(new RowBounds(1, 3))
        .forEach(c -> log.info("Page(1) Coffee {}", c));
    coffeeMapper.findAllWithRowBounds(new RowBounds(2, 3))
        .forEach(c -> log.info("Page(2) Coffee {}", c));

    log.info("===================");

    coffeeMapper.findAllWithRowBounds(new RowBounds(1, 0))
        .forEach(c -> log.info("Page(1) Coffee {}", c));

    log.info("===================");

    coffeeMapper.findAllWithParam(1, 3)
        .forEach(c -> log.info("Page(1) Coffee {}", c));
    List<Coffee> list = coffeeMapper.findAllWithParam(2, 3);
    PageInfo page = new PageInfo(list);
    log.info("PageInfo: {}", page);
  }
}

運行數據入庫和查詢日誌如下:

Page(1) Coffee Coffee(id=1, name=espresso, price=CNY 20.00, createTime=Tue Sep 10 08:50:50 CST 2019, updateTime=Tue Sep 10 08:50:50 CST 2019)
Page(1) Coffee Coffee(id=2, name=latte, price=CNY 25.00, createTime=Tue Sep 10 08:50:50 CST 2019, updateTime=Tue Sep 10 08:50:50 CST 2019)
Page(1) Coffee Coffee(id=3, name=capuccino, price=CNY 25.00, createTime=Tue Sep 10 08:50:50 CST 2019, updateTime=Tue Sep 10 08:50:50 CST 2019)
Page(2) Coffee Coffee(id=4, name=mocha, price=CNY 30.00, createTime=Tue Sep 10 08:50:50 CST 2019, updateTime=Tue Sep 10 08:50:50 CST 2019)
Page(2) Coffee Coffee(id=5, name=macchiato, price=CNY 30.00, createTime=Tue Sep 10 08:50:50 CST 2019, updateTime=Tue Sep 10 08:50:50 CST 2019)
===================
Page(1) Coffee Coffee(id=1, name=espresso, price=CNY 20.00, createTime=Tue Sep 10 08:50:50 CST 2019, updateTime=Tue Sep 10 08:50:50 CST 2019)
Page(1) Coffee Coffee(id=2, name=latte, price=CNY 25.00, createTime=Tue Sep 10 08:50:50 CST 2019, updateTime=Tue Sep 10 08:50:50 CST 2019)
Page(1) Coffee Coffee(id=3, name=capuccino, price=CNY 25.00, createTime=Tue Sep 10 08:50:50 CST 2019, updateTime=Tue Sep 10 08:50:50 CST 2019)
Page(1) Coffee Coffee(id=4, name=mocha, price=CNY 30.00, createTime=Tue Sep 10 08:50:50 CST 2019, updateTime=Tue Sep 10 08:50:50 CST 2019)
Page(1) Coffee Coffee(id=5, name=macchiato, price=CNY 30.00, createTime=Tue Sep 10 08:50:50 CST 2019, updateTime=Tue Sep 10 08:50:50 CST 2019)
===================
Page(1) Coffee Coffee(id=1, name=espresso, price=CNY 20.00, createTime=Tue Sep 10 08:50:50 CST 2019, updateTime=Tue Sep 10 08:50:50 CST 2019)
Page(1) Coffee Coffee(id=2, name=latte, price=CNY 25.00, createTime=Tue Sep 10 08:50:50 CST 2019, updateTime=Tue Sep 10 08:50:50 CST 2019)
Page(1) Coffee Coffee(id=3, name=capuccino, price=CNY 25.00, createTime=Tue Sep 10 08:50:50 CST 2019, updateTime=Tue Sep 10 08:50:50 CST 2019)

PageInfo: PageInfo{pageNum=2, pageSize=3, size=2, startRow=4, endRow=5, total=5, pages=2, list=
  Page{count=true, pageNum=2, pageSize=3, startRow=3, endRow=6, total=5, pages=2, reasonable=true, pageSizeZero=true}
[Coffee(id=4, name=mocha, price=CNY 30.00, createTime=Tue Sep 10 08:50:50 CST 2019, updateTime=Tue Sep 10 08:50:50 CST 2019), 
Coffee(id=5, name=macchiato, price=CNY 30.00, createTime=Tue Sep 10 08:50:50 CST 2019, updateTime=Tue Sep 10 08:50:50 CST 2019)], 
	prePage=1, nextPage=0, isFirstPage=false, isLastPage=true, hasPreviousPage=true, hasNextPage=false, 
	navigatePages=8, navigateFirstPage=1, navigateLastPage=2, navigatepageNums=[1, 2]}



總結

恭喜你,學會了Mybatis分頁工具PageHelper的應用
代碼下載:

https://github.com/zgpeace/Spring-Boot2.1/tree/master/db/DemoDBMybatisPageHelper

參考

https://github.com/pagehelper/Mybatis-PageHelper
https://pagehelper.github.io/docs/howtouse/
https://pagehelper.github.io/
https://github.com/pagehelper/pagehelper-spring-boot

https://github.com/geektime-geekbang/geektime-spring-family/tree/master/Chapter%203/mybatis-generator-demo

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章