Spring Data JPA和Exists查询

时间:2022-09-11 11:54:34

I'm using Spring Data JPA (with Hibernate as my JPA provider) and want to define an exists method with a HQL query attached:

我正在使用Spring Data JPA(Hibernate作为我的JPA提供程序)并且希望定义一个附加了HQL查询的exists方法:

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.

当我运行此查询时,我得到一个java.lang.ClassCastException:java.lang.Long无法强制转换为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?

HQL查询如何使其工作?我知道我可以简单地返回一个Long值,然后检查我的Java代码,如果count> 0,但该解决方法不是必需的,对吧?

7 个解决方案

#1


38  

I think you can simply change the query to return boolean as

我想你可以简单地改变查询以返回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.

PS:如果你检查是否存在基于主键值的CrudRepository已经存在(id)方法。

#2


76  

Spring Data JPA 1.11 now supports the exists projection in repository query derivation.

Spring Data JPA 1.11现在支持存储库查询派生中的exists投影。

See documentation here.

请参阅此处的文档

In your case the following will work:

在您的情况下,以下将起作用:

public interface MyEntityRepository extends CrudRepository<MyEntity, String> {  
    boolean existsByFoo(String foo);
}

#3


6  

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

从Spring数据1.12开始,您可以通过扩展QueryByExampleExecutor接口(JpaRepositoryalready扩展它)来使用Example functionnality的查询。然后你可以使用这个查询(以及其他):

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

考虑一个实体MyEntity作为属性名称,您想知道具有该名称的实体是否存在,忽略大小写,那么对此方法的调用可能如下所示:

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

#4


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


1  

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.

除了公认的答案,我建议另一种选择。使用QueryDSL,创建谓词并使用接受谓词的exists()方法并返回Boolean。

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

QueryDSL的一个优点是您可以将谓词用于复杂的where子句。

#6


0  

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

您可以使用Case表达式在您的选择查询中返回一个布尔值,如下所示。

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

#7


0  

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

您可以在jpaRepository中使用.exists(return boolean)。

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

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

#1


38  

I think you can simply change the query to return boolean as

我想你可以简单地改变查询以返回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.

PS:如果你检查是否存在基于主键值的CrudRepository已经存在(id)方法。

#2


76  

Spring Data JPA 1.11 now supports the exists projection in repository query derivation.

Spring Data JPA 1.11现在支持存储库查询派生中的exists投影。

See documentation here.

请参阅此处的文档

In your case the following will work:

在您的情况下,以下将起作用:

public interface MyEntityRepository extends CrudRepository<MyEntity, String> {  
    boolean existsByFoo(String foo);
}

#3


6  

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

从Spring数据1.12开始,您可以通过扩展QueryByExampleExecutor接口(JpaRepositoryalready扩展它)来使用Example functionnality的查询。然后你可以使用这个查询(以及其他):

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

考虑一个实体MyEntity作为属性名称,您想知道具有该名称的实体是否存在,忽略大小写,那么对此方法的调用可能如下所示:

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

#4


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


1  

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.

除了公认的答案,我建议另一种选择。使用QueryDSL,创建谓词并使用接受谓词的exists()方法并返回Boolean。

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

QueryDSL的一个优点是您可以将谓词用于复杂的where子句。

#6


0  

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

您可以使用Case表达式在您的选择查询中返回一个布尔值,如下所示。

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

#7


0  

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

您可以在jpaRepository中使用.exists(return boolean)。

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

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