David Sykes
David Sykes

Reputation: 7289

How can I dynamically sort a collection property in 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.

Upvotes: 9

Views: 4689

Answers (1)

Felix Leipold
Felix Leipold

Reputation: 1113

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;
}

Upvotes: 3

Related Questions