使用mybatis-plus怎么完成postgres 分页查询
时间: 2024-05-05 17:21:55 浏览: 254
Mybatis-plus 提供了分页插件 `PaginationInterceptor`,可以用于 Postgres 分页查询。下面是一个简单的示例:
首先在 `application.yml` 中配置数据源和 Mybatis-plus:
```yaml
spring:
datasource:
driver-class-name: org.postgresql.Driver
url: jdbc:postgresql://localhost:5432/db_name
username: username
password: password
mybatis-plus:
mapper-locations: classpath*:mapper/*.xml
configuration:
map-underscore-to-camel-case: true
global-config:
db-config:
id-type: auto
table-prefix: t_
plugins:
- com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor
```
在 DAO 层的代码中,可以直接使用 Mybatis-plus 提供的分页方法:
```java
public interface UserMapper extends BaseMapper<User> {
/**
* 分页查询用户
*
* @param page 分页参数
* @param userQuery 查询条件
* @return
*/
IPage<User> selectPage(Page<User> page, @Param("userQuery") UserQuery userQuery);
}
```
其中,`Page` 类是 Mybatis-plus 提供的分页参数类,`IPage` 则是查询结果集的包装类。在 Mapper.xml 文件中,可以按照以下方式进行查询:
```xml
<select id="selectPage" resultType="com.example.entity.User">
select * from t_user
<where>
<if test="userQuery != null">
<if test="userQuery.username != null and userQuery.username != ''">
and username like concat('%', #{userQuery.username}, '%')
</if>
<if test="userQuery.age != null">
and age = #{userQuery.age}
</if>
</if>
</where>
<if test="page != null">
order by id asc
limit #{page.offset}, #{page.size}
</if>
</select>
```
在 Service 层中,可以使用如下方式调用分页查询:
```java
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserMapper userMapper;
@Override
public PageResult<User> findPage(PageParam pageParam, UserQuery userQuery) {
Page<User> page = new Page<>(pageParam.getPageNum(), pageParam.getPageSize());
IPage<User> iPage = userMapper.selectPage(page, userQuery);
return new PageResult<>(iPage.getTotal(), iPage.getRecords());
}
}
```
其中,`PageParam` 是自定义的分页参数类,`PageResult` 则是自定义的分页结果类。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)