Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 283
Stefan Haberl Avatar asked May 22 '15 08:05

Stefan Haberl


People also ask

What is difference between JpaRepository and CrudRepository?

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.

What does findById return in JPA?

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.

How do I stop Spring data JPA from doing a select before a save?

An easy way is to make your Entity implements Persistable (instead of Serializable), which will make you implement the method "isNew".


1 Answers

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); } 
like image 107
Ankit Soni Avatar answered Sep 22 '22 18:09

Ankit Soni