jsr338-experts@jpa-spec.java.net

[jsr338-experts] JPQL: Sorting on optional references

From: Oliver Gierke <ogierke_at_vmware.com>
Date: Tue, 28 Aug 2012 05:44:58 -0700

Hi all,

I just came across a JPQL spec scenario that seems to be a bit weird and I wonder whether there's something we should do about. Suppose you have a Person with optional Addresses:

@Entity
class Person {

  @OneToOne(nullable = true) Address address;
}

@Entity
class Address {
  String city;
}

Now the query scenario here is that we'd like to get all Persons sorted by the Address' city:

select p from Person p left outer join p.address order by p.address.city

Surprisingly, this query will not return Persons not having an Address associated for the following reason: JPA 2.0 spec section 4.4.4. defines path expressions as follows:

> Path expression navigability is composed using “inner join” semantics. That is,
> if the value of a non-terminal field in the path expression is null, the path is
> considered to have no value, and does not participate in the determination of
> the result.

That apparently forces persistence providers into adding an additional inner join to the query which rules out the Persons without Addresses in the first place. I think it's rather unfortunate to have this path expression definition applied to order by clauses as users probably don't expect adding a sort definition would strengthen the actual query criteria. So here are my questions:

1. Why was the path expression navigability defined as such in the first place and not as considering the mapping metadata (nullable = true -> outer join, nullable = false -> inner join). Not saying this is utterly wrong, just want to understand the probably available reasons.
2. Should/can this definition be changed to require consideration of the mapping information? The path expression definition is very much written with the purpose of defining selection criterias which is what they are effectively not used for when used in ORDER BY clauses. The current state leaves JPQL in the weird state that adding a sorting criteria affects the returned items not only in order but also in which items are returned at all, a side-effect which is unpleasant and not easy to grasp.

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
 */