Tran Tam
Tran Tam

Reputation: 699

Spring data jpa repository find by multi elements

I'm using Spring Data JPA in my project. So in repository, I define a list by following:

List<Branch> findByNameContainingAndByTypeContaining(String name, String type)

It works in this case, however, in the search form, I got more than 10 search criteria, it means and in search method, it requires more than 10 elements, and properly, field of them has value.

For example:

name: abc
type: primary
enabled: true
createdBy: null
modifiedBy: null
and so more

for findBy method if I send blank, it works but null value. Moreover, so many fields to search. So I'm looking for a better way to search a form like this. In Grails framework, I can create nameQueries for this but not find a better way in Spring JPA.

Any ideas? Thanks.

Upvotes: 1

Views: 1688

Answers (1)

Systemmanic
Systemmanic

Reputation: 3130

You can use the QueryByExample API, for example:

Branch branch = new Branch();                          
branch.setName("Foo");
branch.setEnabled(true)                           

ExampleMatcher matcher = ExampleMatcher.matching();        
Example<Branch> example = Example.of(branch, matcher);
branchRepository.findAll(example)

You can choose to include or ignore null values, and specify case sensitivity, etc.

More examples are here in the Spring Data Docs.

Upvotes: 2

Related Questions