I have this code to get all transaction between 2 dates. I would like to get a desc sorted list. What are the possibilities?
@Override
public List<Transaction> searchBySubmitDate(final Date startDate,
final Date endDate) {
return transactionRepository.findAll(new Specification<Transaction>() {
@Override
public Predicate toPredicate(Root<Transaction> transaction,
CriteriaQuery<?> q, CriteriaBuilder cb) {
Predicate between = cb.between(transaction.get(Transaction_.dateSubmit), startDate, endDate);
return between;
}
});
@Override
public List<Transaction> searchBySubmitDate(final Date startDate,
final Date endDate) {
return transactionRepository.findAll(new Specification<Transaction>() {
@Override
public Predicate toPredicate(Root<Transaction> transaction,
CriteriaQuery<?> q, CriteriaBuilder cb) {
Predicate between = cb.between(transaction.get(Transaction_.dateSubmit), startDate, endDate);
return between;
}
},new Sort(Direction.DESC,"dateSubmit"));
The repository has another method taking a Sort as additional argument. Call this method with an appropriate Sort instance.
I thought I would leave a more up-to-date answer, since it's been 7 years. This is how we do it now:
interface TransactionRepository extends Repository<Transaction, Long> {
@Query(value = "SELECT * FROM Transaction AS t " +
"WHERE t.date >= :since AND t.date <= :until", nativeQuery = true)
public List<Transaction> findTransactionBetween(@Param("since" String since,
@Param("until" String until);
}
You can read more in the Spring JPA documentation