Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data Repositories - Find where field in list

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.

like image 523
Daniel Avatar asked Jan 17 '16 11:01

Daniel


2 Answers

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

} 
like image 193
james_s_tayler Avatar answered Sep 24 '22 14:09

james_s_tayler


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.

like image 23
jvecsei Avatar answered Sep 23 '22 14:09

jvecsei