MyBatis 分页查询

MyBatis 分页查询MyBatis通过limit关键字或RowBounds类进行分页查询。

大家好,又见面了,我是你们的朋友全栈君。

1. 利用 limit 关键字

接口定义:

public interface AccountMapper { 
   
    // map 类型可以传入多个参数
    List<Account> findPage(Map<String, Integer> param);
}

select 标签:

<select id="findPage" resultMap="pageMap">
    select  * from t_account limit #{offset},#{limit}
</select>

测试:

@Test
public void testFindPage() { 
   
    Map<String, Integer> map = new HashMap<>();
    // 因为 xml 中指定的属性为 offset 和 limit
    // 所以 map 传入的键需与之对应
    map.put("offset", 0);
    map.put("limit", 2);
    List<Account> page = accountMapper.findPage(map);
    System.out.println(page);
}

2. 使用 RowBounds(了解)

接口定义:

public interface AccountMapper { 
   
    // 使用 RowBounds 作为入参
    List<Account> findPage2(RowBounds rowBounds);
}

select 标签:

<select id="findPage2" resultMap="pageMap">
    select * from t_account
</select>

测试:

@Test
public void testFindPage2() { 
   
    RowBounds rowBounds = new RowBounds(0, 2);
    List<Account> accountList = accountMapper.findPage2(rowBounds);
    System.out.println(accountList);
}
  • RowBounds 会将查询出所有满足条件的数据,然后根据 offsetlimit 参数(构造函数入参)取指定区间的数据。
  • 显然当数据庞大时,效率较低。

3. PageHelper 插件

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/136964.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号