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?
Spring Data JPA 1.11 now supports the exists
projection in repository query derivation.
See documentation here.
In your case the following will work:
public interface MyEntityRepository extends CrudRepository<MyEntity, String> {
boolean existsByFoo(String foo);
}