Spring Data JPA 和 Exists 查询 [英] Spring Data JPA and Exists query

查看:50
本文介绍了Spring Data JPA 和 Exists 查询的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 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 cannot be cast to 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 值,然后如果 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 ...")

附注:如果您根据主键值检查是否存在 CrudRepository 已经有 exists(id) 方法.

PS: If you are checking exists based on Primary key value CrudRepository already have exists(id) method.

这篇关于Spring Data JPA 和 Exists 查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆