0

I need to write a service that needs to find an entity using the following combinations: firstName, lastName, phoneNumber, emailAddress

Its becoming a nightmare in my service class and repository to code this. The Permutations are getting out of hand. I still want to use Query Methods to achieve this but was looking to see if there's more efficient way to do this?

public interface UniversitySearchRepository extends CrudRepository<University, Long> {
    public CcCase findByFirstName(
            @Param("firstName") String firstName);
    
    public CcCase findByLastName(
            @Param("lastName") String lastName);
    
    public CcCase findByEmailAddress(
            @Param("emailAddress") String emailAddress);

    public CcCase findByFirstNameAndLastName(
            @Param("firstName") String firstName, 
            @Param("lastName") String lastName);
    
    public CcCase findByFirstNameAndEmailAddress(
            @Param("firstName") String firstName, 
            @Param("emailAddress") String emailAddress);
    
    public CcCase findByLastNameAndEmailAddress(
            @Param("lastName") String lastName, 
            @Param("emailAddress") String emailAddress);
    ....
  • You don't have to prefix the parameter by `@Param` if you haven't annotated the method with `@Query`. For your use case, the [specification API](https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#specifications) could be more efficient – Julien Oct 27 '20 at 13:51

1 Answers1

1

You can try using query-by-example: org.springframework.data.jpa.repository.JpaRepository#findAll(Example<S>)

Related topic: Spring Data JPA: Query by Example?

Petr Aleksandrov
  • 1,434
  • 9
  • 24