membersound
membersound

Reputation: 86747

How to use CrudRepository with variations of parameters?

I want to show a table of persons. The user should be able to send queries and filter by attributes that are mostly optional.

Problem: for each attribute to filter, I'd have to introduce a additional method in spring-data-jpa using `CrudRepository:

public interface PersonRepository extends CrudRepository<Person, Long> {
    List<Person> findByFirstname(firstname);
    List<Person> findbyFirstnameAndLastname(first, last);
    List<Person> findByFirstnameAndLastnameAndAge(first, last, age);
    List<Person> findByFirstnameAndLastnameAndAgeAndCity(first, last, age, city);
}

Question: how could I do better (without having to write native PreparedStatements myself)?

Upvotes: 4

Views: 2801

Answers (3)

Denys Kurochkin
Denys Kurochkin

Reputation: 1495

Query by example allows creating filters by populating simple filter criterias into an "example" entity:

public interface PersonRepository extends CrudRepository<Person, Long> {
    <S extends T> Iterable<S> findAll(Example<S> example);
}

...

Person person = new Person();
person.setFirstname("Dave");
person.setCity("Seattle");
Iterable<Person> davesFromSeattle = personRepository.findAll(Example.of(person));

Upvotes: 3

Irfan Bhindawala
Irfan Bhindawala

Reputation: 333

You just need to set your required properties on entity and pass it to method findAll (Entity entity)

For example if you want employees with some property value then set that parameters on it and pass is to query database.

Employee employee = new Employee ();
employee. setAge (35);
employee. setExperience(5);

Now pass it for query

List <Employee> employèes = do. findAll (Employee);

Upvotes: 0

Ravikumar Rathod
Ravikumar Rathod

Reputation: 129

you use pagination and stream queries for batter result set requirement entity

Upvotes: 0

Related Questions