1. 程式人生 > 實用技巧 >Mybatis-07-分頁

Mybatis-07-分頁

  • 實體類:User

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    public class User {

    private Integer id;
    private String name;
    private String pwd;
    }
  • 方式一:使用limit實現分頁

    • 介面類:UserMapper

      public interface UserMapper {
      List<User> selectLimit(Map<String,Integer> map);
      }
    • 介面的實現類:UserMapper.xml

      <?xml version="1.0" encoding="UTF8" ?>
      <!DOCTYPE mapper
      PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
      "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
      <mapper namespace="com.hmx.mapper.UserMapper">

      <select id="selectLimit" parameterType="map" resultType="User">
      select * from mybatistest limit #{startIndex},#{pageSize};
      </select>
      </mapper>
    • 測試

      public static void selectLimit(){

      SqlSession sqlSession = MybatisUtils.getSqlSession();
      UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

      HashMap<String, Integer> map = new HashMap<String, Integer>();
      map.put("startIndex",1);
      map.put("pageSize",3);
      List<User> userList = userMapper.selectLimit(map);

      for (User user : userList) {
      System.out.println(user);
      }

      sqlSession.close();
      }
  • 方式二:使用RowBounds實現分頁

    • 介面類:UserMapper

      public interface UserMapper {
      List<User> selectRowBounds();
      }
    • 介面的實現類:UserMapper.xml

      <?xml version="1.0" encoding="UTF8" ?>
      <!DOCTYPE mapper
      PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
      "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
      <mapper namespace="com.hmx.mapper.UserMapper">

      <select id="selectRowBounds" parameterType="map" resultType="User">
      select * from mybatistest
      </select>
      </mapper>
    • 測試

        public static void selectRowBounds(){
      SqlSession sqlSession = MybatisUtils.getSqlSession();

      /*
      RowBounds(int offset, int limit)
      RowBounds(開始位置, 查詢個數)
      */
      RowBounds rowBounds = new RowBounds(1, 2);

      /*
      selectList(String var1, Object var2, RowBounds var3)
      selectList(介面類的全限定名.方法名,一般寫null即可, RowBounds物件)
      */
      List<User> userList = sqlSession.selectList("com.hmx.mapper.UserMapper.selectRowBounds", "null", rowBounds);

      for (User user : userList) {
      System.out.println(user);
      }

      sqlSession.close();
      }
  • 方式三:使用分頁外掛PageHelper進行分頁

    如需使用,可參考以下連結:

    如何使用分頁外掛PageHelper