pagehelper分页查询用法
PageHelper是一款MyBatis分页插件,可以帮助我们方便地进行分页查询,使用起来非常简单。下面,我将为大家介绍一下PageHelper的用法。
一、引入依赖
首先,在l文件中添加以下依赖:
```
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper-spring-boot-starter</artifactId>
<version>1.3.0</version>
</dependency>
```
注意:根据自己的具体情况选择对应的版本。
二、配置PageHelper
在l文件中进行以下配置:
```
pagehelper:
helperDialect: mysql
reasonable: true
supportMethodsArguments: true
params: count=countSql
offsetAsPageNum: true
rowBoundsWithCount: true
pageSizeZero: true
returnPageInfo: check
```
- helperDialect:数据库类型,这里使用的是mysql。
- reasonable:启用合理化查询,如果pageNum<1会查询第一页,如果pageNum>pages会查询最后一页。
- supportMethodsArguments:支持通过Mapper接口参数来传递分页参数。
- params:用于从Map或ServletRequest中取值,例如getParam("pageNum"),可以不配置。
- offsetAsPageNum:true代表将RowBounds第一个参数offset当成pageNum页码使用。
-
rowBoundsWithCount:true代表使用RowBounds分页时,会进行count查询。
- pageSizeZero:true代表当pageSize=0或者RowBounds.limit = 0时查询所有结果。
- returnPageInfo:check检查返回类型是否为PageInfo,none返回Page。
三、在Mapper接口中使用
在Mapper接口中定义一个包含分页查询的方法,并使用@Select注解指定SQL语句。例如:
```
@Select("SELECT * FROM user")
List<User> getAllUsers();
```
改成支持分页查询,只需要在方法上加上PageInfo参数:
```
List<User> getAllUsers(PageInfo pageInfo);
```
如果你的SQL查询语句中有占位符,PageHelper也可以支持这种情况。例如:
```
@Select("SELECT * FROM user WHERE name = #{name}")
List<User> getUsersByName(@Param("name") String name, PageInfo pageInfo);
```
四、使用PageHelper进行分页查询
最后,在Service/Controller中使用PageHelper进行分页查询,示例代码如下:
```
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public PageInfo<User> getAllUsers(int pageNum, int pageSize) {
PageHelper.startPage(pageNum, pageSize);
List<User> userList = AllUsers();
return new PageInfo<>(userList);
}
}
```
在这个示例中,我们调用了PageHelper.startPage方法来开启分页查询,pageNum和pageSize分别表示查询的页码和每页显示的条数。这个方法会自动设置分页相关的参数,使得在执行SQL语句时会进行分页查询。
最后,将查询结果封装成PageInfo对象返回即可。分页查询插件
总结
通过上面的介绍,我们了解了PageHelper的基本用法,它可以帮助我们更加方便地进行分页查询,提高我们的开发效率。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论