Spring Data JPA and Exists query

JavaHibernateJpaSpring DataJpql

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

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

Solution 2 - Java

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.

Solution 3 - Java

in my case it didn't work like following

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

You can return it as boolean value with following

@Query(value = "SELECT CASE  WHEN count(pl)> 0 THEN true ELSE false END FROM PostboxLabel pl ...")

Solution 4 - Java

It's gotten a lot easier these days!

@Repository
public interface PageRepository extends JpaRepository<Page, UUID> {

    Boolean existsByName(String name); //Checks if there are any records by name
    Boolean existsBy(); // Checks if there are any records whatsoever

}

Solution 5 - Java

Since Spring data 1.12 you can use the query by Example functionnality by extending the QueryByExampleExecutor interface (The JpaRepositoryalready extends it).
Then you can use this query (among others) :

<S extends T> boolean exists(Example<S> example);

Consider an entity MyEntity which as a property name, you want to know if an entity with that name exists, ignoring case, then the call to this method can look like this :

//The ExampleMatcher is immutable and can be static I think
ExampleMatcher NAME_MATCHER = ExampleMatcher.matching()
			.withMatcher("name", GenericPropertyMatchers.ignoreCase());
Example<MyEntity> example = Example.<MyEntity>of(new MyEntity("example name"), NAME_MATCHER);
boolean exists = myEntityRepository.exists(example);

Solution 6 - Java

Apart from the accepted answer, I'm suggesting another alternative. Use QueryDSL, create a predicate and use the exists() method that accepts a predicate and returns Boolean.

One advantage with QueryDSL is you can use the predicate for complicated where clauses.

Solution 7 - Java

You can use Case expression for returning a boolean in your select query like below.

@Query("SELECT CASE WHEN count(e) > 0 THEN true ELSE false END FROM MyEntity e where e.my_column = ?1")

Solution 8 - Java

Spring data provides method for checking the existence of a row using field: example: boolean existsByEmployeeIdAndEmployeeName(String employeeId, String employeeName);

Solution 9 - Java

You can just return a Boolean like this:

import org.springframework.data.jpa.repository.Query;
import org.springframework.data.jpa.repository.QueryHints;
import org.springframework.data.repository.query.Param;

@QueryHints(@QueryHint(name = org.hibernate.jpa.QueryHints.HINT_FETCH_SIZE, value = "1"))
@Query(value = "SELECT (1=1) FROM MyEntity WHERE ...... :id ....")
Boolean existsIfBlaBla(@Param("id") String id);

Boolean.TRUE.equals(existsIfBlaBla("0815")) could be a solution

Solution 10 - Java

You can use .exists (return boolean) in jpaRepository.

if(commercialRuleMsisdnRepo.exists(commercialRuleMsisdn.getRuleId())!=true){

		jsRespon.setStatusDescription("SUCCESS ADD TO DB");
	}else{
		jsRespon.setStatusCode("ID already exists is database");
	}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionStefan HaberlView Question on Stackoverflow
Solution 1 - JavaAnkit SoniView Answer on Stackoverflow
Solution 2 - JavaK. Siva Prasad ReddyView Answer on Stackoverflow
Solution 3 - JavaRunomuView Answer on Stackoverflow
Solution 4 - JavasparkyspiderView Answer on Stackoverflow
Solution 5 - JavaStephane LView Answer on Stackoverflow
Solution 6 - JavaNarasimhaView Answer on Stackoverflow
Solution 7 - JavaSahil ChhabraView Answer on Stackoverflow
Solution 8 - JavaPrashant RaiView Answer on Stackoverflow
Solution 9 - JavaDogan ErenView Answer on Stackoverflow
Solution 10 - JavaYosua SimanjuntakView Answer on Stackoverflow