I am trying to use dynamic order by but the list retrieved is not ordered

只愿长相守 提交于 2019-12-31 03:50:09

问题


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

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.


回答1:


You cannot pass variables as column name in order by.

There is a work around which may help you achieve what you are trying.

public List<Series> findSeries(int period, String fieldname, int num) {
    String query = "select s from Series s where s.period = "+period+" order by "+fieldname;

     return entityManager.createQuery(query).getResultList();
}

Check this question Hibernate Named Query Order By parameter

There are ways to pass column name in order by in ASP, however I am not able to find anything in Spring or JPA.

"Order By" using a parameter for the column name

http://databases.aspfaq.com/database/how-do-i-use-a-variable-in-an-order-by-clause.html




回答2:


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.

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

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


来源:https://stackoverflow.com/questions/28029806/i-am-trying-to-use-dynamic-order-by-but-the-list-retrieved-is-not-ordered

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!