Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data JPA Query by Example with access to nested Objects Attributes

I use Query by Example and want to know how I can find objects with certain properties in the nested objects.

A plan anyone?

Here is my example Code:

    ExampleMatcher matcher = ExampleMatcher.matching()
      .withMatcher("offer2product.id.productId", match -> match.exact()
              );

    Offer2ProductId id = new Offer2ProductId();
    id.setProductId(1337L);

    Offer2Product offer2Product = new Offer2Product();
    offer2Product.setId(id);

    Set<Offer2Product> offer2productSet = new HashSet<>();
    offer2productSet.add(offer2Product);

    Offer probe = new Offer();
    probe.setOffer2productSet(offer2productSet);

    Example<Offer> example = Example.of(probe, matcher);
    List<Offer> offerList = offerRepository.findAll(example);
like image 742
Martin Avatar asked Nov 08 '22 01:11

Martin


1 Answers

Quoting Spring data documentation: https://docs.spring.io/spring-data/jpa/docs/current/reference/html/#query-by-example

Currently, only SingularAttribute properties can be used for property matching.

In your example, you want to search by a property that is a Set<> (offer2productSet), which is a PluralAttribute - it is not possible to search by this field. It will be ignored when building a query, as can be seen here:

https://github.com/spring-projects/spring-data-jpa/blob/master/src/main/java/org/springframework/data/jpa/convert/QueryByExamplePredicateBuilder.java#L112

like image 75
gosia Avatar answered Nov 18 '22 17:11

gosia