为什么 SpEL 支持在 Spring Data JPA @Query 中不起作用?

Yur*_*hok 3 java spring hibernate spring-el spring-data-jpa

我试图通过将第二个参数传递给具有列表大小的方法来避免冗余。相反,我使用 EL,但出现错误:

org.hibernate.QueryException:并非所有命名参数都已设置:[ $synthetic$__1] [SELECT unique b FROM Book b join b.bookHashtags as ht where ht.hashtagName in :tags group by b.uniqueIdentifier has count(ht.唯一标识符) = : $synthetic$__1]

@Repository
public interface BookRepository extends JpaRepository<Book, Long>, JpaSpecificationExecutor<Book> {
    @Query("SELECT distinct b FROM Book b join b.bookHashtags as ht where ht.hashtagName in :tags " +
        "group by b.uniqueIdentifier having count(ht.uniqueIdentifier) = :#{#tags.size()}")
    List<Book> findAllBooksContainedTags(@Param("tags") Set<String> tags);

}
Run Code Online (Sandbox Code Playgroud)

我使用 spring-data-jpa 1.11.0.RELEASE。我知道这个功能是在1.4版本中开发的。为什么它在我的情况下不起作用......

小智 5

答案很简单:不实现/不支持任意表达式。

请仔细检查 Spring Data JPA 文档中有关使用 SpEL 表达式的内容

从 Spring Data JPA 1.4 版开始,我们支持通过 @Query 在手动定义的查询中使用受限 SpEL 模板表达式

支持的表达式表仅包含

变量:实体名称

用法:从#{#entityName} x中选择x

描述:插入与给定存储库关联的域类型的实体名称。entityName 的解析如下:如果域类型已在 @Entity 注释上设置了 name 属性,则将使用该属性。否则将使用域类型的简单类名。