users@jpa-spec.java.net

[jpa-spec users] [jsr338-experts] Clarification: FETCH JOINs and ORDER BY clauses

From: Oliver Gierke <ogierke_at_vmware.com>
Date: Sun, 20 Jan 2013 10:07:18 +0100

Hi all,

I have a user asking why a query he builds using a fetch clause gets rejected as soon as he's referring to the association declared in the fetch clause:

@Entity
class Person {

  @OneToOne Address address;
}

@Entity
class Address {
  String city;
}

select p from Person p left join fetch p.address where p.firstname = :firstname

works, whereas

select p from Person p left join fetch p.address where p.firstname = :firstname order by p.address.city

fails on Hibernate with the following error message:

"query specified join fetching, but the owner of the fetched association was not present in the select list"

This definitely makes some sense to me as Section 4.4.5.3 of the spec explicitly states:

> The association referenced by the right side of the FETCH JOIN clause must be an association or element collection that is referenced from an entity or embeddable that is returned as a result of the query. It is not permitted to specify an identification variable for the objects referenced by the right side of the FETCH JOIN clause, and hence references to the implicitly fetched entities or elements *cannot appear elsewhere in the query.*

I browsed the spec intensively but couldn't find any discussion of how to combine order by clauses with fetch joins as one obviously has to violate the latter of the two statements if one wants to sort by a property referenced in the fetch clause.

What's the intended way of combining ORDER BY clauses and FETCH JOINs?

Cheers,
Ollie

-- 
/**
 * @author Oliver Gierke - Senior Member Technical Staff
 *
 * @param email ogierke_at_vmware.com
 * @param phone +49-351-30929001
 * @param fax   +49-351-418898439
 * @param skype einsdreizehn
 * @see http://www.olivergierke.de
 */