简体   繁体   中英

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?

You use

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

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

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM