Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring JPA ExampleMatcher compare date condition

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.

like image 690
Tran Tam Avatar asked Aug 31 '17 04:08

Tran Tam


2 Answers

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);
}
like image 196
Yanina Hernández Vega Avatar answered Oct 06 '22 08:10

Yanina Hernández Vega


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

like image 42
Jens Schauder Avatar answered Oct 06 '22 08:10

Jens Schauder