Spring boot query by example with nested object

174 Views Asked by At

I have 2 entities: field and crop. Field looks like this:

public class Field {
  private Integer id;
  private String name;

  @ManyToOne
  @JoinColumn(name = "crop")
  private Crop crop;
}

public class Crop {
  private Integer id;
  private String name;
}

I want to query by example the exact field I get in a request.

public class FieldRequest {
  String name;
  Integer cropId;
}

My service looks like this:

public Optional<Field> getField(FieldRequest request) {
  Field fieldExample = Field.builder()
  .name(request.name)
  .crop(Crop.builder()
    .id(request.cropId)
    .build())
  .build();

  fieldRepository.findOne(Example.of(fieldExample, ExampleMatcher.matching()
        .withIncludeNullValues()
        .withIgnorePaths("id")
        .withMatcher("crop.id", ExampleMatcher.GenericPropertyMatcher::exact
        );
}

my problem is that the query that being created ignores the crop and returns the wrong field. How can I make the query to search by the crop id (I don't care about the crop name), I tried with and without the "Crop.id" matcher.

1

There are 1 best solutions below

0
İsmail Y. On BEST ANSWER

The .withIncludeNullValues() method allows you to include null values in your example query.

Therefore the crop.name field is also added to the query.

You can follow 2 ways: you can ignore the field with .withIgnorePaths("crop.name") or don't use .withIncludeNullValues() at all.

Example 1:

fieldRepository.findOne(
        Example.of(
                fieldExample,
                ExampleMatcher
                        .matching()
                        .withIncludeNullValues()
                        .withIgnorePaths("id")
                        .withIgnorePaths("crop.name")
                        .withMatcher("crop.id", 
                                ExampleMatcher.GenericPropertyMatcher::exact)
        )
);

Example 2:

fieldRepository.findOne(
        Example.of(
                fieldExample,
                ExampleMatcher
                        .matching()
                        .withIgnorePaths("id")
                        .withMatcher("crop.id", 
                                ExampleMatcher.GenericPropertyMatcher::exact)
        )
);