JPA使用@Param注解的空参数仍然会引发错误。

huangapple go评论101阅读模式
英文:

JPA with @Param null parameters still throwing errors

问题

我已经阅读了关于JPA处理空参数的许多帖子。许多解决方案提供了以下使用本机查询的解决方法,请参阅:https://www.baeldung.com/spring-data-jpa-null-parameters

@Query("SELECT c FROM Customer c WHERE (:name is null or c.name = :name) and (:email is null or c.email = :email)")
List<Customer> findCustomerByNameAndEmail(@Param("name") String name, @Param("email") String email);

然而,在我的情况下,这仍然不起作用,当运行测试时,我会得到以下错误:

java.lang.IllegalArgumentException: 参数类型为String的索引0(customer.name中的参数)不能为空!

是否在实体/存储库中需要进行某些配置以防止抛出非法参数?期望的结果将是对空值的“忽略”,并在那种情况下将所有内容都返回给我。

我已经意识到以下问题:https://jira.spring.io/browse/DATAJPA-209 仍然没有解决。

英文:

I've read a number of posts on here relating to JPA handling of null params.

Many solutions have offered the following workaround using native queries, see: https://www.baeldung.com/spring-data-jpa-null-parameters

@Query(&quot;SELECT c FROM Customer c WHERE (:name is null or c.name = :name) and (:email is null or c.email = :email)&quot;)
List&lt;Customer&gt; findCustomerByNameAndEmail(@Param(&quot;name&quot;) String name, @Param(&quot;email&quot;) String email);

However this still doesn't work in my case I get the following error when running a test

java.lang.IllegalArgumentException: Parameter of type String at index 0 in customer.name must not be null!

Is there something in the entity/repo that needs configured to prevent throwing the illegal args. Desired outcome would be "ignoring" of null value and just return me everything in that case.

I am aware of the following: https://jira.spring.io/browse/DATAJPA-209 still unresolved.

答案1

得分: 1

请尝试添加 Nullable 注解 -

@Query("SELECT c FROM Customer c WHERE (:name is null or c.name = :name) and (:email is null or c.email = :email)")
List<Customer> findCustomerByNameAndEmail(@Nullable @Param("name") String name, @Nullable @Param("email") String email);
英文:

Please try adding Nullable annotation -

@Query(&quot;SELECT c FROM Customer c WHERE (:name is null or c.name = :name) and (:email is null or c.email = :email)&quot;)
List&lt;Customer&gt; findCustomerByNameAndEmail(@Nullable @Param(&quot;name&quot;) String name, @Nullable @Param(&quot;email&quot;) String email);

huangapple
  • 本文由 发表于 2020年10月16日 18:53:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/64387769.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定