但检索到的列表未排序

但检索到的列表未排序

本文介绍了我正在尝试使用动态排序,但检索到的列表未排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public List<Series> findSeries(int period, String fieldname, int num) {
    TypedQuery<Series> query = em.createQuery(
            "select s from Series s where  s.period = ?1 order by ?2",
            Series.class);
    query.setParameter(1, period);
    query.setParameter(2, fieldname);
    query.setMaxResults(num);
    return query.getResultList();
}

这是我正在使用的方法.我认为 order by 甚至没有被执行,即使我传递了不正确的字段名,它也不会给出任何错误.

This is the method I am using. I think order by isn't even getting executed, it doesn't give any error even when I pass incorrect fieldname.

推荐答案

当涉及到动态限制和排序时,最好使用 PagingAndSortingRepository,所以现在我的 Repository 扩展了这个存储库.我可以简单地使用 JPA 条件查询,如下所示.

When it comes to dynamic limit and ordering, its best to use PagingAndSortingRepository so now my Repository extends this repository. I can simply use JPA criteria query as below.

如果您想了解有关 JPA 标准查询的更多信息,我发现这非常有用 http://docs.spring.io/spring-data/data-jpa/docs/1.0.x/reference/html/#jpa.query-methods.query-creation

If u want to learn more about JPA criteria query i found this very helpful http://docs.spring.io/spring-data/data-jpa/docs/1.0.x/reference/html/#jpa.query-methods.query-creation

 @Repository
public interface SeriesRepository extends PagingAndSortingRepository<Series,Long>{
List<Series> findByPeriod(int period, Pageable pageable);
}

然后,当我从我的 dao 调用此方法时,我可以实例化 PageRequest,它是 Pageable 的实现之一.我可以为这个实例添加限制和排序顺序.

And then when I call this method from my dao i can just instantiate PageRequest which is one of the implementation of Pageable. I can add limit and sorting order to this instance.

public List<Series> getSeriesByFilter(int period, String fieldname, int num) {
    Sort sort = new Sort(Sort.Direction.ASC, fieldname);
    Pageable pageable = new PageRequest(0, num, sort);
    return seriesRepo.findByPeriod(period, pageable);
}

这篇关于我正在尝试使用动态排序,但检索到的列表未排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 21:43