Spring JPA ExampleMatcher compare date condition

14k views Asked by At

I'm using Spring JPA and get list of data by using Example Matcher. Source code below:

public Page<TranxLog> findAllByConditions(TranxReportFormModel formModel, Pageable page) {
        ExampleMatcher matcher = ExampleMatcher.matching()
                .withNullHandler(ExampleMatcher.NullHandler.IGNORE)
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
                .withIgnoreCase()
                .withIgnoreNullValues();
        Example<TranxLog> example = Example.of(formModel.getTranxLog(), matcher);
        return tranxlogRepository.findAll(example, page);
    }

Now, I have search page, which have formDate and toDate and it has to be compared with field DateTime in TranxLog. I tried to use .withMatcher() but cannot find a way to compare a date.

Any idea? Thanks.

2

There are 2 answers

2
Jens Schauder On

You can't do that with query-by-example. Probably the best is to construct a Specification

1
Yanina Hernández Vega On

You can extends from JpaSpecificationExecutor too and get the Predicate with QueryByExamplePredicateBuilder from Example.

In your repository:

public interface TranxlogRepository extends JpaRepository<Tranxlog, Long>, JpaSpecificationExecutor<Tranxlog>{ 
}

In your serviceImp

public Specification<TranxLog> getSpecFromDatesAndExample(
  LocalDateTime from, LocalDateTime to, Example<TranxLog> example) {

    return (Specification<TranxLog>) (root, query, builder) -> {
         final List<Predicate> predicates = new ArrayList<>();

         if (from != null) {
            predicates.add(builder.greaterThan(root.get("dateField"), from));
         }
         if (to != null) {
            predicates.add(builder.lessThan(root.get("dateField"), to));
         }
         predicates.add(QueryByExamplePredicateBuilder.getPredicate(root, builder, example));

         return builder.and(predicates.toArray(new Predicate[predicates.size()]));
    }
};

In your serviceImp too:

public Page<TranxLog> findAllByConditions(TranxReportFormModel formModel, Pageable page) {
    ExampleMatcher matcher = ExampleMatcher.matching()
            .withNullHandler(ExampleMatcher.NullHandler.IGNORE)
            .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING)
            .withIgnoreCase()
            .withIgnoreNullValues();
    Example<TranxLog> example = Example.of(formModel.getTranxLog(), matcher);
    return tranxlogRepository.findAll(getSpecFromDatesAndExample(from, to, Example.of(formModel.getTranxLog(), matcher)), page);
}