Spring Data Repositories - Find where field in list

Daniel picture Daniel · Jan 17, 2016 · Viewed 31k times · Source

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.

Answer

james_s_tayler picture james_s_tayler · Jan 17, 2016

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);

}