Search code examples
javahibernatejpajpql

JPQL order by one of ElementCollection


I have following entities:

Article
| 
+- @Id long id
|
+- @ElementCollection Map<Language, Translation> translations

Translation
|
+- @Column String name

What I would like to achieve is to fetch a list of Articles, ordered by name in given Language.

Something like:

SELECT a FROM Article a 
JOIN a.translations t WHERE t.language = ? 
ORDER BY t.name

The problem is that when using t.language throws "could not resolve property" exception, even though the language column exists in the Translations database table.

How can I achieve this behaviour?


Solution

  • I think this is not supported by Hibernate. I would simply make Translation an entity rather than an embedded, and include a language field in the Translation entity.

    The mapping would be

     @OneToMany
     @JoinColumn(name = "article_id")
     @MapKey(name = "language")
     private Map<Language, Translation> translations;
    

    The association could also be bidirectional, and your query could then be much more logical and less dangerous, because it could return translations rather than articles:

    select t from Translation t 
    inner join fetch t.article 
    where t.language = :language 
    order by t.name