Search code examples
javaspring-data-jpajpqlhibernate-criteriacriteria-api

JAVA Criteria API I need to get the Time Passed From a specfic Date


I need to select all the available records in database where creation date only passed 5 days for more description . I need to get all orders that time passed after creation 1 day or 2 days.

I mean can I subtract the creation date from the current date in the predicate object and then check if it equals the time passed or not.

int passedDays = 5;
Page<Order> orders = orderRepository.findAll(new Specification<Order>() {
    @Override
    public Predicate toPredicate(Root<Order> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
        List<Predicate> predicates = new ArrayList<>();
        // where created - now date = passedDays 
        predicates.add(cb.equal(root.<Date>get("createdAt"),passedDays));
        return cb.and(predicates.toArray(new Predicate[predicates.size()]));
    }
},pageable);

Solution

  • You should be using between Restriction:

    int passedDays = 5;
    
    @Override
    public Predicate toPredicate(Root<AuditTrail> root, CriteriaQuery<?> query,
                                             CriteriaBuilder cb) {
    
        List<Predicate> predicates = new ArrayList<>();
    
        Instant now = Instant.now();
        Instant then = now.minus(passedDays, ChronoUnit.DAYS);
        
        predicates.add(cb.between(root.get("createdAt"), then, now));
    
        // if your createdAt has type java.util.Date or java.sql.Date
        // predicates.add(cb.between(root.get("createdAt"), Date.from(then), Date.from(now)));
    
        return cb.and(predicates.toArray(new Predicate[predicates.size()]));            
    }