20

I'm trying to use spring PagingAndSortingRepository with a find MyEntity where field in fieldValues query as follows:

@Repository
public interface MyEntity extends PagingAndSortingRepository<MyEntity, String> {

    List<MyEntity> findByMyField(Set<String> myField);

}

But of no success.

I expected the above function to return all entities whose field matches one of the field values but it only returns empty results.

Even though it seems like a pretty straight forward ability i could not find any reference to it in the docs.

Is / How that could be achieved?

Thanks.

Daniel
  • 6,194
  • 7
  • 33
  • 59
  • I want to search by a list and a string , i.e my mehtod has 2 paramemeters a list and a string , will it work ? , If yes how shall I name my method – Varun Sood Sep 24 '18 at 07:44

2 Answers2

29

This should indeed be possible if you are searching on a specific field within your entity and you want to return a list of all that field matches at least one entry in some collection. The documentation here says this can be achieved using the keyword In example: findByAgeIn(Collection<Age> ages) and is equivalent to … where x.age in ?1

From your post i'm not 100% sure if this is the use case you are after but give this a try. You will need to search on a specific field, so replace 'field' with whatever field you are searching on. If you are searching on multiple fields it may be possible to concatenate the results with the Or keyword and specify multiple fields that way.

@Repository
public interface MyEntity extends PagingAndSortingRepository<MyEntity, String> {

    List<MyEntity> findByFieldIn(Set<String> myField);

} 
james_s_tayler
  • 1,823
  • 1
  • 15
  • 20
6

http://docs.spring.io/spring-data/jpa/docs/current/reference/html/

Your method name has to be findByMyFieldIn so you got to add an In at the end to get a where ... in (..) query.

jvecsei
  • 1,936
  • 2
  • 17
  • 24