我将 Spring Data Rest 与 org.springframework.boot 1.5.2 与 hibernate 5.2.9 一起使用。我想要实现的是一种使用 JPA 来查询排序、过滤、可分页的方法,它可以返回实体的子集或返回投影。
下面是使用的代码: (1) 过滤规范 (2) 投影和摘录以在集合中应用投影 (3) 尝试返回 Page 的控制器,但它仅在返回类型为 Page 时才有效。其中 Student 是实体,StudentLite 是投影
问题是:(1)如何有一个返回页面投影的查询+排序+过滤器(2)可以将摘录应用于该查询?(3) 有什么方法可以在@RepositoryRestController 中使用@JsonView 来解决?
StudentRepository 类
@RepositoryRestResource(excerptProjection = StudentLite.class)
public interface StudentRepository extends PagingAndSortingRepository<Student,Long>,
JpaSpecificationExecutor<Student> {}
和 StudentSpecification 类
public class StudentSpecification {
public static Specification<Student> filteredStudentList(StudentSearch c) {
final StudentSearch criteria = c;
return new Specification<Student>() {
@Override
public Predicate toPredicate(Root<Student> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
Join<Student, Contact> joinContact = root.join(Student_.contact);
Path<Contact> contact = root.get(Student_.contact);
Path<String> officialId = root.get(Student_.officialId);
Path<String> name = root.get(Student_.name);
Path<String> email = contact.get(Contact_.email);
Path<String> phoneMobile = contact.get(Contact_.phoneMobile);
final List<Predicate> predicates = new ArrayList<Predicate>();
if(criteria.getOfficialId()!=null) {
predicates.add(cb.like(officialId, "%" + criteria.getOfficialId() + "%"));
System.out.println("==not null...criteria.getOfficialId()="+criteria.getOfficialId()+" :officialId="+officialId.toString());
}
if(criteria.getName()!=null) {
predicates.add(cb.like(name, "%"+criteria.getName()+"%"));
}
if(criteria.getEmail()!=null) {
predicates.add(cb.like(email, "%"+criteria.getEmail()+"%"));
}
if(criteria.getPhoneMobile()!=null) {
predicates.add(cb.like(phoneMobile, "%"+criteria.getPhoneMobile()+"%"));
}
return cb.and(predicates.toArray(new Predicate[predicates.size()]));
}
};
}
}
以及使用 @ExposesResourceFor(Student.class) 和 @RepositoryRestController 注释类的控制器:
@RequestMapping(method=RequestMethod.GET)
public @ResponseBody Page<StudentLite> getStudentList(Pageable pageable, @RequestParam Map<String,String> criteria) {
StudentSearch ss = new StudentSearch(criteria);
// Below statement fail, as findAll(...) is suppose to return Page<Student>
Page<StudentLite> pagedStudentLite = studentRep.findAll( StudentSpecification.filteredStudentList(ss), pageable);
return pagedStudentLite;
}