Spring Data JPA and Exists query

匿名 (未验证) 提交于 2019-12-03 01:23:02

问题:

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 {    @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?

回答1:

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.



回答2:

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 {       boolean existsByFoo(String foo); } 


回答3:

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

 boolean exists(Example 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 example = Example.of(new MyEntity("example name"), NAME_MATCHER); boolean exists = myEntityRepository.exists(example); 


回答4:

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 ...") 


回答5:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!