JPA findAll(spec,Sort)

2020-06-25 05:30发布

问题:

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;
        }
    });

回答1:

@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"));


回答2:

The repository has another method taking a Sort as additional argument. Call this method with an appropriate Sort instance.



回答3:

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