我可以在Spring Data JPA存储库方法中将@Query定义与规范结合使用吗? [英] Can I combine a @Query definition with a Specification in a Spring Data JPA repository method?

查看:213
本文介绍了我可以在Spring Data JPA存储库方法中将@Query定义与规范结合使用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在一种存储库方法中同时使用@Query注释和规范?例如,我想要一个这样的方法:

Is it possible to use both @Query annotation and specification in one repository method? For example I'd like to have a method like this:

@Query(value="SELECT e from EMPLOYEE where firstName <> ?1")
public Page<Employee> findEmployeeBySomethigFancy(String firstName, Pageable pageable, Specification<Employee> emp);

是否可以或应该将整个查询构建为Predicate并删除@Query批注?

Is it possible or should I build the whole query as a Predicate and remove the @Query annotation?

推荐答案

首先,您应该阅读其次,根据 JpaSpecificationExecutor 接口,您的存储库应实现该接口,以下方法采用Specification自变量:

  • count(Specification<T> spec)
  • List<T> findAll(Specification<T> spec)
  • Page<T> findAll(Specification<T> spec, Pageable pageable)
  • List<T> findAll(Specification<T> spec, Sort sort)
  • T findOne(Specification<T> spec)
  • count(Specification<T> spec)
  • List<T> findAll(Specification<T> spec)
  • Page<T> findAll(Specification<T> spec, Pageable pageable)
  • List<T> findAll(Specification<T> spec, Sort sort)
  • T findOne(Specification<T> spec)

因此,您不能将@Query定义与Specification混合使用.

So, you can't mix a @Query definition with a Specification.

但是,由于可以使用Specification表示firstName <> ?1条件,并且由于可以组合任意数量的规范,因此只能使用Specification重写整个@Query.

However, since you can express the firstName <> ?1 condition using a Specification and because you combine as many specifications as you want, you can rewrite the whole @Query using Specification(s) only.

这篇关于我可以在Spring Data JPA存储库方法中将@Query定义与规范结合使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆