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

查看:29
本文介绍了我可以在 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?

推荐答案

首先,你应该阅读这个 Spring 博客文章.

First thing, you should read this Spring blog post.

第二,根据JpaSpecificationExecutor 接口,您的存储库应实现该接口,以下方法采用 Specification 参数:

  • count(Specification spec)
  • 列表findAll(Specification spec)
  • 页面findAll(Specification spec, Pageable pageable)
  • 列表findAll(Specification spec, Sort sort)
  • T findOne(Specification spec)

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

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

但是,由于您可以表示 firstName <>?1 条件使用 Specification 并且因为您可以根据需要组合任意数量的规范,所以您可以使用 Specification 重写整个 @Query>(s) 只.

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天全站免登陆