问题描述
我正在使用Spring Data JPA(以Hibernate作为我的JPA提供程序),并希望使用附加的HQL查询定义 exists
方法:
I'm using Spring Data JPA (with Hibernate as my JPA provider) and want to define an exists
method with a HQL query attached:
public interface MyEntityRepository extends CrudRepository<MyEntity, String> {
@Query("select count(e) from MyEntity e where ...")
public boolean existsIfBlaBla(@Param("id") String id);
}
当我运行这个查询时,得到一个 java.lang.ClassCastException:java.lang.Long不能转换为java.lang.Boolean
。
When I run this query, I get a java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Boolean
.
HQL查询必须看起来像做这个工作?我知道我可以简单地返回一个Long值,然后检查我的Java代码,如果 count> 0
,但该解决方法不应该是必需的,对吧?
How does the HQL query have to look like to make this work? I know I could simply return a Long value and afterwards check in my Java code if count > 0
, but that workaround shouldn't be necessary, right?
推荐答案
我认为您可以简单地将查询更改为返回布尔值
I think you can simply change the query to return boolean as
@Query("select count(e)>0 from MyEntity e where ...")
PS:
如果您正在检查基于主键值 CrudRepository
的存在是否已存在 (id)
方法。
PS:If you are checking exists based on Primary key value CrudRepository
already have exists(id)
method.
这篇关于Spring Data JPA和Exists查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!