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?
CrudRepository provides CRUD functions. PagingAndSortingRepository provides methods to do pagination and sort records. JpaRepository provides JPA related methods such as flushing the persistence context and delete records in a batch.
Its findById method retrieves an entity by its id. The return value is Optional<T> . Optional<T> is a container object which may or may not contain a non-null value. If a value is present, isPresent returns true and get returns the value.
An easy way is to make your Entity implements Persistable (instead of Serializable), which will make you implement the method "isNew".
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With