1

For example a user repository,

interface PersonRepository extends Repository<User, Long> {      
   List<Person> findByEmailAddressAndLastname(EmailAddress emailAddress, String lastname); 
}

Is there a way to achieve findByEmailAddressAndLastname(null, "lastname") = findByLastname("lastname"), because after I add more parameters in user entity, the number of method name query increase exponentially. I want to reduce the redundancy. Thanks.

JasminDan
  • 523
  • 2
  • 6
  • 14
  • your question is unclear. do you mind explaining, what do you meant by `findByEmailAddressAndLastname(null, "lastname") = findByLastname("lastname")` – pvpkiran Mar 13 '18 at 14:53
  • @pvpkiran If I pass a null parameter, I want the method to return all entity without filtering that parameter. – JasminDan Mar 13 '18 at 15:03
  • @JasminDan if you have many properties and you need to have filter on them IMO it's better to use QueryDsl: https://stackoverflow.com/a/48596145 – Cepr0 Mar 13 '18 at 16:16
  • Check [`@Query`](https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#jpa.query-methods.at-query) which will help you to achieve what you want. – Ram Mar 13 '18 at 17:39

1 Answers1

1

Since spring-data-jpa 2 you can use @Nullable annotation:

   List<Person> findByEmailAddressAndLastname(@Nullable EmailAddress emailAddress, String lastname); 

Check nullability annotations to see all the variants

lucsbelt
  • 453
  • 2
  • 9
  • If I pass a null parameter, does it compare entity parameter with null value or just does not compare it at all? – JasminDan Mar 14 '18 at 13:07
  • if you pass a null parameter the query will be "emailAddress is null". To achieve your approach i suggest that use find by example from JpaRepository: List findAll(Example example); like this: User user = new User(); user.setEmailAddress (emailAddress); user.setLastName(lastname); List results = personRepository.findAll(Example.of(user)); – lucsbelt Mar 14 '18 at 13:48