Java 如何使用 Spring CrudRepository 查询布尔属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23827412/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 01:26:14  来源:igfitidea点击:

How to query for boolean property with Spring CrudRepository?

javaspringspring-dataspring-data-jpa

提问by membersound

I'm using Spring CrudRepositoryfor database queries. How can I create a method signature (not writing SQL select statement myself) for a boolean property?

我正在使用 SpringCrudRepository进行数据库查询。如何为布尔属性创建方法签名(不是自己编写 SQL select 语句)?

The following does not work:

以下不起作用:

class MyEntity {
       private boolean active;
}


interface MyEntityRepository implements CrudRepository<MyEntity, Long> {
   List<MyEntity> findActive(); //or also: findNotActive();
}

采纳答案by geoand

I would do:

我会做:

interface MyEntityRepository implements CrudRepository<MyEntity, Long> {
   List<MyEntity> findByActive(Boolean active);
}

Then the service layer would be

那么服务层将是

public class MyEntityServiceImpl implements MyEntityService{


   public List<MyEntity> findActive() {
      return myEntityRepository.findByActive(true);
   }
}

UPDATE

更新

As pointed out by @OliverGierke you could simplify your repository even more by doing:

正如@OliverGierke 所指出的,您可以通过以下方式进一步简化您的存储库:

interface MyEntityRepository implements CrudRepository<MyEntity, Long> {
   List<MyEntity> findByActiveTrue(); //you could also use findByActiveFalse
}

For all the supported keywords you should see the section

对于所有支持的关键字,您应该看到该部分

Query creation

查询创建

of the reference documentation

所述的参考文献