bug-record06: jpa分页查询

问题描述01

jpa分页查询,error:Page 1 of 0 containing UNKNOWN instances, 查出来的数据库数据与javabean不匹配

	/**
	* page = 1
	* size = 10
	* isAsc = true
	*/
	PageRequest.of(page, size, isAsc ? Sort.Direction.ASC : Sort.Direction.DESC, orderField)

原因分析01:

提示:这个问题一般是你分页查询,page为1(page默认从0开始),但没有1页(也就是没有第二页),所以你应该page从0开始赋值;


解决方案01:

	public Pageable getDefaultPageable(Integer page, Integer size, Boolean isAsc, String orderField) {
        page--;
        if (page < 0) {
            page = 0;
        }
        if (size < 0) {
            size = 0;
        }
        return PageRequest.of(page, size, isAsc ? Sort.Direction.ASC : Sort.Direction.DESC, orderField);
    }

// 或者:page-1即可
	PageRequest.of(--page, size, isAsc ? Sort.Direction.ASC : Sort.Direction.DESC, orderField)
您好!关于Spring Data JPA分页查询,您可以按照以下步骤进行操作: 1. 首先,确保您的项目中已经引入了Spring Data JPA依赖,以及相关的数据库驱动依赖。 2. 创建一个继承自JpaRepository的接口,用于定义您的数据访问操作。例如: ```java import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; @Repository public interface UserRepository extends JpaRepository<User, Long> { // 在这里可以定义各种自定义的查询方法 } ``` 3. 在您的Service层或者Controller层注入该Repository,并使用其提供的分页方法进行查询。例如: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.stereotype.Service; @Service public class UserService { @Autowired private UserRepository userRepository; public Page<User> getUsersByPage(int pageNum, int pageSize) { PageRequest pageRequest = PageRequest.of(pageNum, pageSize); return userRepository.findAll(pageRequest); } } ``` 在上述示例中,我们通过调用`userRepository.findAll(pageRequest)`方法实现了分页查询,并传入`PageRequest`对象来指定页码和每页大小。 4. 最后,在您的Controller层中使用该Service方法来处理分页查询请求,并将结果返回给前端。例如: ```java import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { @Autowired private UserService userService; @GetMapping("/users") public Page<User> getUsersByPage(@RequestParam int pageNum, @RequestParam int pageSize) { return userService.getUsersByPage(pageNum, pageSize); } } ``` 在上述示例中,我们通过`@RequestParam`注解来接收前端传递的pageNum和pageSize参数,并调用UserService中的方法进行查询。 这样,您就可以使用Spring Data JPA进行分页查询了。希望能对您有所帮助!如果您还有其他问题,请随时提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mr朱墨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值