JPA findAll(spec,Sort)

时间:2011-12-26 16:44:53

标签: jpa spring-data

我有这个代码来获取2个日期之间的所有交易。我想得到一个desc排序列表。有什么可能性?

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

3 个答案:

答案 0 :(得分:8)

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

答案 1 :(得分:0)

存储库有another method taking a Sort as additional argument。使用适当的Sort实例调用此方法。

答案 2 :(得分:0)

我想我会留下一个最新的答案,因为已经7年了。这就是我们现在的做法:

val myRepo: MyRepository by inject()

您可以在Spring JPA documentation

中阅读更多内容