buræquete
buræquete

Reputation: 14688

Sort feature in association endpoint in Spring Data Rest

I have the following two resources, and their association;

@Table(name = "Item")
@Data
@Entity
public class Item {

    @ManyToOne
    @JoinColumn(name = "fk_wrapper")
    private Wrapper wrapper;

    @Id
    @GeneratedValue
    private String id;

    private Integer someValue;
}

and;

@Table(name = "Wrapper")
@Data
@Entity
public class Wrapper {

    @Id
    @GeneratedValue
    private String id;

    @OneToMany(cascade = CascadeType.ALL)
    @JoinColumn(name = "fk_wrapper")
    private List<Item> items;

    private String someField;
}

Then, first, I create a Wrapper;

POST http://localhost:8080/wrappers/
{
    "someField": "asd"
}

http://localhost:8080/wrappers/1 created, then I create two Item's, linked to this Wrapper;

POST http://localhost:8080/items/
{
    "someValue": "5",
    "wrapper": "http://localhost:8080/wrappers/1"
}

&

POST http://localhost:8080/items/
{
    "someValue": "7",
    "wrapper": "http://localhost:8080/wrappers/1"
}

After all this, when I call the endpoint http://localhost:8080/wrappers/1/items, I get the list of these two items, as expected, but what the trouble is that, I cannot seem to have a sorting feature on this endpoint. I seem to be able to sort in http://localhost:8080/items endpoint, but while fetching with association, there doesn't seem to be a sorting feature. Is this lack of sorting is intended, or am I lacking some configuration?


P.S. when I create a custom search method, for example;

@RepositoryRestResource
public interface ItemRepository extends JpaRepository<Item, String> {
    List<Item> findByWrapper_Id(@Param("id") String id, Sort sort);
}

Then I can use the sorting with http://localhost:8080/items/search/findByWrapper_Id endpoint, but too ugly imo, considering there is already an auto-generated endpoint.

Upvotes: 4

Views: 737

Answers (1)

Davi Cavalcanti
Davi Cavalcanti

Reputation: 353

Spring Data Rest doesn't support sorting on the associations.

You seem to have already found the best way to do what you need, according to the Spring Data Rest team - create a query for fetching the data you need. That will indeed support both pagination and sorting.

The reason why it's not supported has to do with the time when the queries are made to fetch the main resource (before the association endpoints are built) and the facts that the association endpoint makes use of the the loaded entity associations directly and that for supporting sort, a new query would need to be made anyway.

More detailed information can be found here:

https://jira.spring.io/browse/DATAREST-725?focusedCommentId=122244&page=com.atlassian.jira.plugin.system.issuetabpanels%3Acomment-tabpanel#comment-122244

Cheers!

Upvotes: 1

Related Questions