查询方法中的Spring Data可选参数

标签 spring hibernate spring-data spring-data-jpa jpql

我想在存储库层写一些查询方法。此方法必须忽略空参数。例如:

List<Foo> findByBarAndGoo(Bar barParam, @optional Goo gooParam);

此方法必须按此条件返回 Foo:

bar == barParam && goo == gooParam;

如果 gooParam 不为空。如果 gooParam 为空,则条件更改为:

bar == barParam;

有什么解决办法吗?有人可以帮助我吗?

最佳答案

我不相信您能够使用查询定义的方法名称方法来做到这一点。来自文档(reference):

Although getting a query derived from the method name is quite convenient, one might face the situation in which either the method name parser does not support the keyword one wants to use or the method name would get unnecessarily ugly. So you can either use JPA named queries through a naming convention (see Using JPA NamedQueries for more information) or rather annotate your query method with @Query

我认为您遇到了这种情况,因此下面的答案使用了 @Query 注释方法,这几乎与方法名称方法 ( reference ) 一样方便。

    @Query("select foo from Foo foo where foo.bar = :bar and "
        + "(:goo is null or foo.goo = :goo)")
    public List<Foo> findByBarAndOptionalGoo(
        @Param("bar") Bar bar, 
        @Param("goo") Goo goo);

关于查询方法中的Spring Data可选参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32745673/

相关文章:

java - 当我想在集合中保存多个bean时,是否需要在Spring中同步@Autowired方法?

Spring boot服务下载文件

java - org.hibernate.AnnotationException 映射错误

未调用 Spring Boot @RepositoryEventHandler

java - 为什么我看不到通过 Spring Data JPA 的更新查询发出的更改?

java - 未使用 CORS 的 Spring Yml 配置

spring - 使用 Spring Boot 拦截器重定向

java - Hibernate 缓存导致@Cacheable 实体的低百分比性能下降?

java - liquibase - 如何设置 text[] 数组的默认值?

JPA findAll(规范,排序)