【问题标题】:Spring Data JPA repositories: IN-clause in derived query not workingSpring Data JPA 存储库:派生查询中的 IN 子句不起作用
【发布时间】:2014-12-27 22:18:09
【问题描述】:

我有一个如下所示的存储库:

public interface UserRepository extends JpaRepository<User, Long>
{
    User findByEmailIgnoreCase(String email);

    @Query("select u from User u where u.id in (:ids)")
    Set<User> getByIdInSet(@Param("ids") Set<Long> ids);
}

当我调用getByIdInSet 时,我收到以下错误:

Caused by: java.lang.IllegalArgumentException: You have attempted to set a value of type class org.eclipse.persistence.indirection.IndirectSet for parameter ids with expected type of class java.lang.Long from query string select u from User u where u.id in (:ids).
    at org.eclipse.persistence.internal.jpa.QueryImpl.setParameterInternal(QueryImpl.java:933)
    at org.eclipse.persistence.internal.jpa.EJBQueryImpl.setParameter(EJBQueryImpl.java:593)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)

显然我不知道是什么意思,因为我已经尝试更改各种数据类型,但仍然得到相同的错误。我传递的一组 id 只包含一个 id。请指出正确的方向。

【问题讨论】:

    标签: java jpa spring-data spring-data-jpa


    【解决方案1】:

    不带括号试试

    @Query("select u from User u where u.id in :ids")
    

    【讨论】:

    • 看起来有效,谢谢。为什么有些地方需要在集合周围加上括号?我还有其他几个需要括号的存储库,我能看到的唯一区别是括号在实体的集合上,而不是在参数上。这就是区别吗?
    • 我的参考是this post,它说你不需要带有集合值参数的括号。显然,Hibernate 在不同版本中的行为不同,不了解 EclipseLink。找不到任何关于此的官方 JPA 参考,如果我找到了,我会更新我的答案。
    • Here 是关于此的另一篇文章,参考了 Hibernate 错误,参数周围带有必需的括号。
    【解决方案2】:

    最新版本的 Spring Data JPA 支持 IN 关键字,可用于创建如下查询:

    Set<User> findByIdIn(Set<Long> ids);
    

    【讨论】:

    • 此外,尽管 Set 是 IN 子句的最佳选择(以强制唯一性),但也接受可变参数; Set&lt;User&gt; findByIdIn(Long... ids);
    猜你喜欢
    • 2019-03-02
    • 1970-01-01
    • 2016-08-26
    • 2012-06-02
    • 1970-01-01
    • 2015-10-13
    • 2021-11-04
    • 2015-12-29
    • 1970-01-01
    相关资源
    最近更新 更多