Joe Taras Joe Taras - 4 months ago 28
Java Question

Spring data JPA custom repository, how apply logic

I try to implement a JPA custom repository.

I have a filter object like this:

public class FilterPatient {
private String surname;
private String name;
private String cf;

... and so on

From front end I create an instance of FilterPatient based on user input.

So, user, for example, can value surname and cf properties or surname and name, and so on

I want to implement a custom repository as follow:

PatientRepository extends JpaRepository<Patient, Long> {
List<Patient> findBySurname(String surname);

List<Patient> findByName(String name);

List<Patient> findByCf(String cf);

// custom methods:
@Query("select p from Patient p where = :name
and p.surname = :surname")
List<Patient> findByNameAndSurname(@Param("name") String name,
@Param("surname") String surname);

... and so on


Based on user input I must execute a different query, so how I manage the repository? I must write query methods to cover different combinations of input field and in the service I must write the logic about method repository call? Or I can parametrize better my custom method query?

Other infos:

Without spring-data normally, I define a DAO method with input parameter
, so I build a query based on parameter not null and then I substitute parameter with
method. In this way I write one generic method, is it possible with Spring-data and JPA repositories?


You have a lot of built-in ways to create custom queries, for example findByNameAndSurname will work without the @Query annotation..

enter image description here