您的位置:首页 > 其它

使用srpingJPA进行分页,排序和模糊查询

2018-03-10 22:00 411 查看
使用srpingJPA进行分页,排序和模糊查询,原生SQL
分页和排序

模糊查询

原生SQL

使用srpingJPA进行分页,排序和模糊查询,原生SQL

分页和排序

SpringJPA是使用
PageRequest
来进行分页查询的,
PageRequest
有三个构造方法,

并且排序的页码是从零开始的。

//单纯根据页码和页码大小
public PageRequest(int page, int size) {
this(page, size, (Sort)null);
}

//直接根据Direction 和字段名进行排序
public PageRequest(int page, int size, Direction direction, String... properties) {
this(page, size, new Sort(direction, properties));
}

//根据sort对象进行排序
public PageRequest(int page, int size, Sort sort) {
super(page, size);
this.sort = sort;
}


例子

//单纯根据页码和页码大小
Pageable pageable = new PageRequest(page,pageSize);

//直接根据Direction 和字段名进行排序
Pageable pageable=new PageRequest(page, pageSize,Sort.Direction.DESC,"createDate");

//根据sort对象进行排序
Sort sort = new Sort(Sort.Direction.DESC,"createDate");
Pageable pageable = new PageRequest(page,pageSize,sort);

TestReposity.findAll(pageable);


模糊查询

模糊查询需要
Repository
接口继承
JpaSpecificationExecutor<T>
接口。

public interface TestRepository extends JpaRepository<Student, Integer>,JpaSpecificationExecutor<Student>{


使用
JpaSpecificationExecutor<T>
Page<T> findAll(Specification<T> var1, Pageable var2);
构造方法

Page<Student> pageWebSite=StudentRepository.findAll(new Specification<Student>() {

@Override
public Predicate toPredicate(Root<Student> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
Predicate predicate=cb.conjunction();
if(student!=null){
if(StringUtil.isNotEmpty(student.getName())){
predicate.getExpressions().add(cb.like(root.get("name"), "%"+student.getName().trim()+"%"));
}
if(student.getAge()!=null && student.getAge()>1){
predicate.getExpressions().add(cb.equal(root.get("age"), student.getAge()));
}
}
return predicate;
}
}, pageable);
return pageWebSite.getContent();
}


原生SQL

在Repository接口中写

@Query(value="SELECT * FROM student WHERE score<?1 ORDER BY id DESC LIMIT 1",nativeQuery=true)
public Student getScoreLowerStudent(Integer score);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: