9

I am doing a Spring web app and I use Spring Data.

I am able to use Spring Data to find objects by a single value of a field. For example:

some_object_repository.findByFirstName("John") 

Is there any way I can provide two first names (e.g., "John", "David") similar to the following in concept:

some_object_repository.findByFirstName({"John", "David"})

without me writing a custom implementation?

Regards and thanks!

curious1
  • 14,155
  • 37
  • 130
  • 231

1 Answers1

17

You can do this with In at the end

findByAgeIn(Collection ages) … where x.age in ?1

http://docs.spring.io/spring-data/jpa/docs/1.6.0.RELEASE/reference/html/jpa.repositories.html#jpa.query-methods

Section 2.3.2 Query creation

In your case it will be

findByFirstNameIn(Collection names)

mavarazy
  • 7,562
  • 1
  • 34
  • 60
  • Thanks so much for the pointer. It is helpful! Just one more question: is it possible to do a single value in one field, and two or more values (IN) in another field at the same time? – curious1 May 28 '14 at 04:48
  • As far as I remember, there should be no problems with that. It will look like something like this: findByEmailAddressAndLastnameIn(String email, Collection lastNames) – mavarazy May 28 '14 at 04:52
  • 1
    Is there a way to do %LIKE% search with an IN clause? – Rahul kalivaradarajalu Aug 14 '19 at 11:52
  • 1
    @Rahulkalivaradarajalu no! there is no chance to use `like` within `in` conditions. You can use completely different approach by using `containing` for more info visit the following link: https://stackoverflow.com/a/3016918/3881354 and the above-mentioned Spring Data JPA's doc. – Elyas Hadizadeh Feb 21 '21 at 05:54