java-Spring Data JPA和存在查询
我正在使用Spring Data JPA(将Hibernate作为我的JPA提供程序),并想定义一个count > 0附加了HQL查询的方法:
public interface MyEntityRepository extends CrudRepository {
@Query("select count(e) from MyEntity e where ...")
public boolean existsIfBlaBla(@Param("id") String id);
}
当我运行此查询时,我得到count > 0。
如何使HQL查询看起来很有效? 我知道我可以简单地返回一个Long值,然后在我的Java代码中检查是否为count > 0,但是这种解决方法不是必需的,对吧?
7个解决方案
131 votes
Spring Data JPA 1.11现在在存储库查询派生中支持exists投影。
请参阅此处的文档。
在您的情况下,以下方法将起作用:
public interface MyEntityRepository extends CrudRepository {
boolean existsByFoo(String foo);
}
Ankit Soni answered 2020-07-04T20:35:52Z
58 votes
我认为您可以简单地更改查询以将布尔值返回为
@Query("select count(e)>0 from MyEntity e where ...")
PS:如果要检查是否存在基于主键值的CrudRepository,则已经具有exists(id)方法。
K. Siva Prasad Reddy answered 2020-07-04T20:35:23Z
9 votes
就我而言,它不像下面那样工作
@Query("select count(e)>0 from MyEntity e where ...")
您可以使用以下命令将其作为布尔值返回
@Query(value = "SELECT CASE WHEN count(pl)> 0 THEN true ELSE false END FROM PostboxLabel pl ...")
Runomu answered 2020-07-04T20:36:16Z
8 votes
从Spring数据1.12开始,您可以通过扩展2952073487327927953920接口来使用示例功能查询(2952073487387353953921已经扩展了它)。
然后,您可以使用此查询(以及其他查询):
boolean exists(Example example);
考虑一个实体MyEntity,该实体作为属性name,您想知道是否存在一个具有该名称的实体,忽略大小写,那么对该方法的调用如下所示:
//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);
Stephane L answered 2020-07-04T20:36:45Z
2 votes
除了可接受的答案之外,我还建议另一种选择。使用QueryDSL,创建一个谓词,并使用exists()方法来接受一个谓词并返回布尔值。
QueryDSL的优点之一是您可以将谓词用于复杂的where子句。
Narasimha answered 2020-07-04T20:37:10Z
1 votes
您可以使用Case表达式在您的选择查询中返回boolean,如下所示。
@Query("SELECT CASE WHEN count(e) > 0 THEN true ELSE false END FROM MyEntity e where e.my_column = ?1")
Sahil Chhabra answered 2020-07-04T20:37:30Z
-3 votes
您可以在jpaRepository中使用.exists(返回布尔值)。
if(commercialRuleMsisdnRepo.exists(commercialRuleMsisdn.getRuleId())!=true){
jsRespon.setStatusDescription("SUCCESS ADD TO DB");
}else{
jsRespon.setStatusCode("ID already exists is database");
}
Yosua Simanjuntak answered 2020-07-04T20:37:49Z