spring jpa查询可分页,排序和过滤以及返回投影

时间:2017-06-29 04:05:32

标签: spring spring-data-jpa spring-data-rest projection jpa-criteria

我正在使用带有hibernate 5.2.9的org.springframework.boot 1.5.2的Spring Data Rest。我想要实现的是一种使用JPA查询sort,filter,pageable的方法,可以返回实体的子集或返回一个投影。

以下是使用的代码: (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> {}

学生指定课程

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;
    }

0 个答案:

没有答案