Spring Boot JPA分页 PageRequest.of代替过时的PageRequest方法

Spring Boot JPA分页 PageRequest.of代替过时的PageRequest方法

该篇博客记录了关于Spring Data JPA之  new PageRequest遇到的问题

最近在学习Spring Data Jpa数据持久层这一块知识的时候,在编些dao接口的单元测试类的时候回用到pageable分页能,发现在 new PageRequest时发现该方法已经被启用。

 

看到这里,不由的去查看pageRequest的源码,看到下面发现,定义了关于PageRequest of的static (静态)方法(废话少说,先上源码):

public static PageRequest of(int page, int size) {
		return of(page, size, Sort.unsorted());
	}

	/**
	 * Creates a new {@link PageRequest} with sort parameters applied.
	 *
	 * @param page zero-based page index.
	 * @param size the size of the page to be returned.
	 * @param sort must not be {@literal null}.
	 * @since 2.0
	 */
	public static PageRequest of(int page, int size, Sort sort) {
		return new PageRequest(page, size, sort);
	}

	/**
	 * Creates a new {@link PageRequest} with sort direction and properties applied.
	 *
	 * @param page zero-based page index.
	 * @param size the size of the page to be returned.
	 * @param direction must not be {@literal null}.
	 * @param properties must not be {@literal null}.
	 * @since 2.0
	 */
	public static PageRequest of(int page, int size, Direction direction, String... properties) {
		return of(page, size, Sort.by(direction, properties));
	}

看到这里,终于了解了,以后要实现分页功能的时候,不要用new PageRequest()方法,而是直接调用PageRequest.of方法。

 

解决方案:

代替分页功能的方法是不要new PageRequest,而是直接调用PageRequest.of这个方法,并根据你的有需求选择参数

对比一下我写的小测试类下new PageRequest和PageRequest.of的方法:

原来:

  /**
     * PagingAndSortingRepository分页测试
     */
    @Test
    @Transactional
    public void testPagingAndSortingRepositoryPaging(){

        //Pageable:封装了分页的参数,当前页,每页的显示的条数。注意:他的当前页是从0开始
        Pageable pageable = new PageRequest(0,10);

        Page<Users> page = this.usersRepositoryPagingAndSorting.findAll(pageable);
        System.out.println("总条数:"+page.getTotalElements());
        System.out.println("总页数:"+page.getTotalPages());
        List<Users> list =page.getContent();
        for (Users users:list){
            System.out.println(users);
        }
    }

最终:

  /**
     * PagingAndSortingRepository分页测试
     */
    @Test
    @Transactional
    public void testPagingAndSortingRepositoryPaging(){

        //Pageable:封装了分页的参数,当前页,每页的显示的条数。注意:他的当前页是从0开始
        
        Pageable pageable = PageRequest.of(0,5);
        Page<Users> page = this.usersRepositoryPagingAndSorting.findAll(pageable);
        System.out.println("总条数:"+page.getTotalElements());
        System.out.println("总页数:"+page.getTotalPages());
        List<Users> list =page.getContent();
        for (Users users:list){
            System.out.println(users);
        }
    }

最后运行查看效果:

  • 17
    点赞
  • 33
    收藏
    觉得还不错? 一键收藏
  • 6
    评论
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值