Ray Toal
Ray Toal

Reputation: 88378

How to write JPARepository query where a query parameter is a list?

The documentation for Spring Data's JPARepository provides examples such as

List<User> findByLastname(String lastname);

for and SpringData will do all the work generating the proper query and the correct users will be returned.

But suppose I want to get 50 users and I have a list of their last names. I don't want to call the above method 50 times. I would like to call the JPA equivalent of

select *
from user
where last_name in ('N0', 'N1', 'N2'... 'N49');

Now looking at the documentation I see some possibilities such as named queries and specifications. The named queries seem to require specifying SQL in a Java annotation. The specifications used with the findAll methods have is and hasMoreThan type methods in the examples, but I don't see any that would turn into in queries. And the Javadocs for specifications don't have any example usage.

How does one create a method in a JPARepository to query by a list of possibilities?

Upvotes: 2

Views: 3483

Answers (2)

Macubex Splongk
Macubex Splongk

Reputation: 1

Create an array of lastname that you want to make as query parameter. Then try this: findAllInLastName(List lastNames); The Spring data automatically search a suitable query method when you extend the JpaRepository class as long as you follow the right format of creating a query method name. Hope this helps you. And try to read the Spring Data online documentation. Cheers brother!

Upvotes: 0

Desorder
Desorder

Reputation: 1539

You use

List<User> findByLastnameIn(Collection<String> lastnames);

More here. (Table4, 5th to last row)

Upvotes: 6

Related Questions