Search code examples
jpaquerydsl

Dynamic sorting in QueryDSL


Lets say I have an Entity:

@Entity
public class Person {
    @Id
    private int id;
    private String name;
    private Date birthdate;
}

and I would like to have method which will return OrderSpecifier for a field of this entity based on String parameter which will be name of one of entities fields.

/**
 * fieldName - name of field from Person entity
 */
private OrderSpecifier<?> getSortedColumn(Order order, String fieldName){
    //how to implement this???        
}

Solution

  • I actualy managed to do it like this:

    /**
     * fieldName - name of field from Person entity
     */
    private OrderSpecifier<?> getSortedColumn(Order order, String fieldName){
        Path<Object> fieldPath = Expressions.path(Object.class, QPerson.person, fieldName);     
        return new OrderSpecifier(order, fieldPath);
    }