Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring queryByExample with Range between

I have Spring Application with a repository

interface EventRepository extends JpaRepository<Event, Long>, QueryByExampleExecutor<Event> { }

Event e = new Event();
e.setTest('ABC');

eventRepository.findAll(Example.of(e), pageable);

Is working great and I am almost there. But I need to restrict to a date range between 'from' and 'to'

I have seen some post that it is not working with QBE but this was in 2015.

I have created a Range object but I don't know how to apply it.

http://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/domain/Range.html

I can not use the default spring way like

@Transactional
interface EventRepository extends JpaRepository<Event, Long>, QueryByExampleExecutor<Event> {

    def findBetween(Date lower, Date upper)

}

because I have a bunch of dynamic search parameters.

like image 891
Pascal Avatar asked Jan 12 '17 07:01

Pascal


1 Answers

You can extends from JpaSpecificationExecutor<T> too and get the Predicate with QueryByExamplePredicateBuilder from Example<T>. Keeping in mind that birthdateField belongs to the Event entity.

public Specification<Event> getSpecFromDatesAndExample(
      LocalDateTime from, LocalDateTime to, Example<Event> example) {
return (Specification<Event>) (root, query, builder) -> {
  final List<Predicate> predicates = new ArrayList<>();

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

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

}

And use Specification in findAll with JpaSpecificationExecutor.

List<Event> events = eventRepository.findAll(getSpecFromDatesAndExample(from, to, Example.of(Event)));
like image 85
Manuel Larrota Avatar answered Oct 06 '22 01:10

Manuel Larrota