如何使用 Spring CrudRepository 查询布尔属性? [英] How to query for boolean property with Spring CrudRepository?

查看:28
本文介绍了如何使用 Spring CrudRepository 查询布尔属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

以下不起作用:

class MyEntity {
       private boolean active;
}


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

推荐答案

我会这样做:

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

那么服务层就是

public class MyEntityServiceImpl implements MyEntityService{


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

更新

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

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

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

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

For all the supported keywords you should see the section

查询创建

参考文档

这篇关于如何使用 Spring CrudRepository 查询布尔属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆