javahibernatejpaspring-datajpql

Spring Data JPA and Exists query


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);

}

When I run this query, I get a java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Boolean.

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?


Solution

  • I think you can simply change the query to return boolean as

    @Query("select count(e)>0 from MyEntity e where ...")
    

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