Skip to Main Content

Integration

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Sorting on one-to-many relationship with JPA criteria API

815658Nov 24 2010 — edited Nov 30 2010
I'm having some trouble using JPA criteria API with collection references.

I have an entity called Competence that has a one-to-many relation to CompetenceName that contains names for Competence for several languages.
[Competence.java]
@OneToMany(mappedBy="competence", cascade=CascadeType.ALL, orphanRemoval=true)
private List<CompetenceName> competenceNames;

[CompetenceName.java]
@ManyToOne @JoinColumn(name = "competence_id", referencedColumnName = "id")
private Competence competence;

@ManyToOne @JoinColumn(name = "lang_id", referencedColumnName = "id")
private Language language;

@Basic @Column(name = "name", length = 50)
private String name

Now I want to load 200 Competence-entities and sort them by their name (depending on the language of the logged in user). How would this be done using the JPA Criteria API? With a normal query, I would accomplish this with

"SELECT DISTINCT c FROM Competence AS c LEFT JOIN c.competenceNames AS cn ORDER BY cn.name"

Obviously, CompetenceName could contain zero entries for a Competence, but it works anyway with a normal query. With criteria API, it would look something like:

CriteriaQuery<Competence> cq = cb.createQuery(Competence.class);
Root<Competence> competence = cq.from(Competence.class);
competence.fetch(Competence_.competenceNames);
cq.select(competence).orderBy(cb.asc(competence.get(Competence_.competenceNames).get(CompetenceName_.name)); // Doesn't work

Is this even possible to do without creating a normal query?

Edited by: 812655 on Nov 24, 2010 2:32 AM
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 28 2010
Added on Nov 24 2010
1 comment
1,985 views