Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Data JPA sorting on nested collection

I have the following domain objects:

@Entity
public class Item {

   @Id
   @GeneratedValue(strategy = GenerationType.AUTO)
   private Long id;
   private String name;

   @OneToMany
   private List<PropertyDefinition> propertyDefinitions;
}

@Entity
public class PropertyDefinition {

   @Id
   private Long id;

   private final String name;
   private final String value;
}

I would like to sort the items for example "title" named PropertyDefinition.value

How could I do that with Spring Data JPA?

Iterable<Item> items = itemRepository.findAll(new Sort("???"));

example code can be found here:
https://github.com/altfatterz/sort-poc/

Any feedback appreciated.

like image 319
Zoltan Altfatter Avatar asked Dec 03 '22 22:12

Zoltan Altfatter


1 Answers

You can use the JPA or Hibernate @OrderBy annotation:

@OneToMany
@OrderBy("value ASC") // sort by value ASC
private List<PropertyDefinition> propertyDefinitions;

Otherwise, you can create your own query to sort them with Criteria or HQL Query.

like image 177
Sotirios Delimanolis Avatar answered Dec 19 '22 11:12

Sotirios Delimanolis