How can I dynamically sort a collection property in JPA?
java, jpa
Solution
You could sort them in java. Possibly in a getter:
List<Region> getRegions(){
sorted = new List<Regions>(regions);
Collections.sort(sorted, new RegionComparator(getUserLanguage()));
return sorted;
}
Problem
We have the following JPA class: ``` @Entity class Supplier { // ... id property etc. @OneToMany @OrderBy("someProperty") private List<Region> regions; } ``` This works fine in the normal case. However, we have some multi-lingual data where the values are stored in properties like `nameEn`, `nameDe`, `nameZh`. The exact property to use depends on the logged in user. For example, a German speaking user should see the regions as if it had been annotated with `@OrderBy("nameDe")`. How can I achieve this? I am aware I could sort the collection in my code after it has been loaded, but this makes pagination of the results quite difficult.