Search code examples
javaspring-data-jpapageable

How to accept @OrderBy of JPA sort value as a dynamic parameter?


I want to sort a nested collection property dynamically based on the query parameter sort.

Suppose i have an entity A as

class A{

@OneToMany(mappedBy="a")
private Set<B> bset;

}

class B{

private LocalDate datefield;
@ManyToOne
private C c;

}

class C
{
private Double quantity;

}

I am calling repository of A with findAll(Specification specification,Pageable page)

From UI, rest controller is called with sort param as below pattern

 url?page=0&size=10&sort=bset_datefield

As it is a nested collection,the above sort is not working. The sortable fields are datefield,quantity.

I know @OrderBy("bset.datefield") will work,but the parameter should be dynamic.

How can i achieve this when invoking find All on A repository ?


Solution

  • It cannot be done because when the entityManager is initialized the annotations are evaluated.

    The best options are, create a query that comes ordered or once the list is obtained if you use Java 8 from now on, order with the sort method of stream.