Search code examples
javasqlspringhibernateentitymanager

Entity Manager ORDER BY query with Sort Object


I am using the Entity-Manager and want to append the "ORDER BY" query comming from the Sort (org.springframework.data.domain.sort) Object.

The Sort object contains something like "id: DESC". i can parse the Sort object as a String removing the condition and appending it to my query. the query would looks like this "SELECT p FROM projects ... ORDER BY p.id DESC"

Is there a better way to tackle this problem, any suggestions?


Sorry maybe my description is a bit missleading but i have a REST api and my method gets the Sort object inlcuding the field i need to order by and the direction. I cant easily order it ASC or DESC. its depending on the Sort object i own with the method usage.


Solution

  • Last week, i was checked for the same issue and changed my code as like below: it was worked Fine;sharing the same to you.

    StringBuilder strBuilder = "SELECT p FROM projects";
    entityManager.createQuery(strBuilder.toString());  
    Iterator<Order> orderIterator = sort.iterator();
    Order order = orderIterator.next();
    strBuilder.append(" Order By ").append(order.getProperty()).append(" ")
                    .append(order.getDirection().name());