Sorting dynamic localized data
I've been working on a Java EE 6 project (EJB 3.1, JSF 2, JPA 2) for some time now and I cannot figure out a good way to sort dynamic localized data. With dynamic localized data, I mean a user created object with a name in one or several languages. To be more concrete, imagine a database table called X containing just an id (There's more columns ofc, this is just to simplify it), another table containing available languages, and one table binding the two together by putting a name on X for every language.
[x]
id integer PRIMARY KEY
[lang]
id integer PRIMARY KEY
[x_names]
x_id integer FOREIGN KEY REFERENCES x.id
lang_id integer FOREIGN KEY REFERENCES lang.id
name
PRIMARY KEY (x_id, lang_id)
[X.java]
@Id private Integer id;
@OneToMany(mappedBy="x", cascade=CascadeType.ALL, orphanRemoval=true)
private List<XName> names;
Now i'd like to present these objects sorted by name (while preserving the MVC model) for a user for a language chosen by this user. If the x-object lacks a name in this language, the name of a default language should be shown. X-objects will always have a name in at least one language (although there is no way to specify this database wise).
Java sorting seems kind of out of the question since the x-entity should not know what language is currently used and thus compareTo cannot do its job, so it feels like sorting in the database makes most sense. My first idea looked something like this:
SELECT DISTINCT x FROM X x LEFT JOIN x.names n ORDER BY n.name
This however makes no sense since no language is specified it will sometimes sort on one language, sometimes another.
This is the best that i've been able to come up with:
SELECT DISTINCT x FROM X x LEFT JOIN x.names n LEFT JOIN n.language l ORDER BY l.id, cn.name
Which could work in theory, always selecting the names from the lowest language id, enabling me to work in a priority order that way. The problem here is that DISTINCT does not work, I get one x-object f开发者_运维百科or every name in the system. Could I perhaps send down the chosen language to the model layer and use it somehow while still getting ALL x objects, not just the ones with a language available? Any ideas would be appreciated.
The logic of all this is for a view where a user can organize these x-objects and easily fill in a name at any and all languages, while still seeing x-objects even if they dont have a name in the users language so that they can add one.
JPA provider is EclipseLink.
I realize now that sorting in the controller layer makes more sense, and skip database sorting completely. I just realized that you can implement your own comparator with Collections.sort which can have access to what language is currently selected and sort after that.
精彩评论