原生分页
@Testpublic void test1() { Pageable pageable =new PageRequest(0, 5); Page<User> datas = userService.findAll(pageable); System.out.println("总条数:"+datas.getTotalElements()); System.out.println("总页数:"+datas.getTotalPages()); for(User u : datas) { System.out.println(u.getId()+"===="+u.getUserName()); } }
注意:继承了JpaRepository
后的IUserService
拥有了findAll
的重载方法,当传入参数为Pageable
时,返回传则是一个分页的对象Page
。
在创建Pageable
接口的实例时需要指定其子类PageRequest
,在PageRequest
类中有几个构造函数:
public PageRequest(int page, int size) { this(page, size, (Sort)null); } public PageRequest(int page, int size, Direction direction, String... properties) { this(page, size, new Sort(direction, properties)); } public PageRequest(int page, int size, Sort sort) { super(page, size); this.sort = sort; }
page
:当前页码 (这个页码是从0开始的 )size
:每页获取的条数direction
:排序方式,ASC、DESCproperties
:排序的字段sort
:排序对象
Sort 是
import org.springframework.data.domain.Sort; //弃用构造器有 /** @deprecated */ @Deprecated public Sort(Sort.Order... orders) { this(Arrays.asList(orders)); } /** @deprecated */ @Deprecated public Sort(List<Sort.Order> orders) { Assert.notNull(orders, "Orders must not be null!"); this.orders = Collections.unmodifiableList(orders); } /** @deprecated */ @Deprecated public Sort(String... properties) { this(DEFAULT_DIRECTION, properties); } // 推荐的 public Sort(Sort.Direction direction, String... properties) { this(direction, (List)(properties == null ? new ArrayList() : Arrays.asList(properties))); } public Sort(Sort.Direction direction, List<String> properties) { if (properties != null && !properties.isEmpty()) { this.orders = new ArrayList(properties.size()); Iterator var3 = properties.iterator(); while(var3.hasNext()) { String property = (String)var3.next(); this.orders.add(new Sort.Order(direction, property)); } } else { throw new IllegalArgumentException("You have to provide at least one property to sort by!"); } }
例子:
public interface ThemeRepository extends JpaRepository<Theme, Long> { /** * 查找所有没有被删除的 * * @param deleteFlag * @return */ Page<Theme> findByDeleteFlag(int deleteFlag, Pageable pageable); }
使用
Sort sort = new Sort(Sort.Direction.DESC, "createDate","themeName"); Pageable pageable = PageRequest.of(page - 1, limit, sort); return themeService.findByDeleteFlag(deleteFlag, pageable);
还没有评论,来说两句吧...