Spring Data JPA仓库:派生查询中的IN子句不起作用

9

我有一个仓库,它看起来像这样:

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。请指引我正确的方向。

2个回答

16

不使用括号试一试

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

1
看起来好像行了,谢谢。为什么有些地方需要在集合周围加括号?我有几个其他的存储库需要这些括号,我唯一能看到的区别是这些括号在实体的集合上而不是参数上。这是区别吗? - jensengar
1
我的参考资料是这篇帖子,其中提到在使用集合参数时不需要括号。显然,Hibernate在不同的版本中表现不同,我不知道EclipseLink是否也是如此。我没有找到任何官方的JPA参考资料,如果我找到了什么,我会更新我的答案。 - Predrag Maric
2
这里有另一个关于此问题的帖子,提到了Hibernate bug需要在参数周围加上必需的括号。 - Predrag Maric

14

Spring Data JPA 的最新版本支持使用 IN 关键字创建如下所示的查询:

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

2
此外,虽然可以接受可变参数,但在涉及IN子句(以强制唯一性)时,Set是最佳选择; Set<User> findByIdIn(Long... ids); - Youness

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接