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

最后运行查看效果:

Spring Boot JPA分页 PageRequest.of代替过时的PageRequest方法_第1张图片

你可能感兴趣的:(Spring,Boot)