简体   繁体   中英

How to query for boolean property with Spring CrudRepository?

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?

The following does not work:

class MyEntity {
       private boolean active;
}


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

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM