Tomasz Mularczyk
Tomasz Mularczyk

Reputation: 36179

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???        
}

Upvotes: 6

Views: 5699

Answers (2)

Mr.Cat
Mr.Cat

Reputation: 330

Another way to do it using the field path that works with any Q type

    public static OrderSpecifier<?> getSortColumn(EntityPathBase<?> entity, Order order, String fieldName) {

        final var entityPath = new PathBuilder<>(entity.getType(), entity.getMetadata().getName());
        final var sortColumnPath = entityPath.getComparable(fieldName, Comparable.class); //All sorting columns should be implementing Comparable

        return switch (order) {
            case ASC -> sortColumnPath.asc();
            case DESC -> sortColumnPath.desc();
        };
    }

I'm making use of some Java 17+ features, but you can still do without.
then use it with any Q type i.e.

getSortColumn(QPerson.person, "name");
getSortColumn(QCat.cat, "dateOfBirth");

and you don't have to manually construct new instance of OrderSpecifier and deal with 'use of raw type' warnings.

Upvotes: 0

Tomasz Mularczyk
Tomasz Mularczyk

Reputation: 36179

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

Upvotes: 13

Related Questions