Created
September 13, 2018 08:40
-
-
Save guozi/7ca0689807f6e153846403289bdfd605 to your computer and use it in GitHub Desktop.
Spring Data Jpa 分页查询
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 分页 | |
* 应用查询提示@QueryHints,这里是在查询的适合增加了一个comment | |
* 查询结果是lastName和firstName都是bauer这个值的数据 | |
*/ | |
@RequestMapping("/pageable") | |
public void pageable(){ | |
//Pageable是接口,PageRequest是接口实现 | |
//PageRequest的对象构造函数有多个,page是页数,初始值是0,size是查询结果的条数,后两个参数参考Sort对象的构造方法 | |
Pageable pageable = new PageRequest(0,3, Sort.Direction.DESC,"id"); | |
Page<Customer> page = repository.findByName("bauer",pageable); | |
//查询结果总行数 | |
System.out.println(page.getTotalElements()); | |
//按照当前分页大小,总页数 | |
System.out.println(page.getTotalPages()); | |
//按照当前页数、分页大小,查出的分页结果集合 | |
for (Customer customer: page.getContent()) { | |
System.out.println(customer.toString()); | |
} | |
System.out.println("-------------------------------------------"); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 一个参数,匹配两个字段 | |
* @param name2 | |
* @Param pageable 分页参数 | |
* @return | |
* 这里Param的值和=:后面的参数匹配,但不需要和方法名对应的参数值对应 | |
* 这里增加了@QueryHints注解,是给查询添加一些额外的提示 | |
* 比如当前的name值为HINT_COMMENT是在查询的时候带上一些备注信息 | |
*/ | |
@QueryHints(value = { @QueryHint(name = HINT_COMMENT, value = "a query for pageable")}) | |
@Query("select c from Customer c where c.firstName=:name or c.lastName=:name") | |
Page<Customer> findByName(@Param("name") String name2,Pageable pageable); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment