javaspringspring-dataspring-data-jdbc

Spring Data: how do I sort an embedded collection of entities?


I have entity Contract, which holds a list of Deals inside. I model them in the following way:

public class Contract {

    @Id
    private Long id;
    @MappedCollection(idColumn = "CONTRACT_TO_DEAL", keyColumn = "CONTRACT_TO_DEAL_INDEX")
    private List<Deal> deals= new ArrayList<Deal>();
}

I can easily get my Contract with all linked Deals using Contract repository:

public interface ContractRepository extends ListCrudRepository<Contract, Long>

I know I can get sorted Deals using Deals repository via Sort, Paging, adding OrderBy etc.

The question is: Is there a way to configure my setup in order to get Contract with Deals sorted using standard methods of Contract repository? I.e. if I get Contract by Id, I obtain Contract with Deals ordered?

In other words, each time I need Contract, I need it with Deals sorted by creation date. I never need Contract with Deals sorted in other way, or unsorted.


Solution

  • Spring Data JDBC stores the list index with the referenced entity in the column specified by MappedCollection.keyColumn and thereby fixes the ordering to whatever it was when persisting the aggregate.

    If you want to change the sorting, you'll have to rearrange the entries in the list and persist it again.