Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I dynamically sort a collection property in JPA?

Tags:

java

jpa

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.

like image 672
David Sykes Avatar asked Dec 08 '10 17:12

David Sykes


1 Answers

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;
}
like image 76
Felix Leipold Avatar answered Oct 06 '22 00:10

Felix Leipold