jsr338-experts@jpa-spec.java.net

[jsr338-experts] Re: query improvements: downcasting

From: Adam Bien <abien_at_adam-bien.com>
Date: Tue, 8 Mar 2011 10:39:35 +0100

On 07.03.2011, at 21:45, Linda DeMichiel wrote:

> As promised, we'll kickoff our work with some of the hopefully easier
> items to get us warmed up. We'll start with some topics in the query
> area.
>
> First up -- downcasting.
>
>
> We've gotten a number of requests to support a downcasting functionality
> in the query language. This is useful particularly for polymorphic
> relationships where the intent is to access subtype-specific attributes.
>
> SQL supports this via the TREAT ... AS operator:
>
> TREAT (expression AS datatype)

o.k. because of SQL. As Java developer I would rather call it more explicitly like DOWNCAST ... TO. This would introduce another keyword and increase complexity...
>
> where datatype is a subtype of the static type of the expression.
>
>
> The extension of this syntax to JPQL would be straightforward.
>
> For example,
>
> SELECT b.name, b.ISBN
> FROM Order o JOIN TREAT(o.product AS Book) b
>
> SELECT e FROM Employee e JOIN TREAT(e.projects AS LargeProject) lp
> WHERE lp.budget > 1000
>
> SELECT e FROM Employee JOIN e.projects p
> WHERE TREAT(p AS LargeProject).budget > 1000 OR
> TREAT(p AS SmallProject).name LIKE "Persist%" OR
> p.description LIKE "COST OVERRUN"
>
>
> An open issue however is the handling of the case where the
> instance passed to TREAT is not of the same type or a subtype of the
> specified datatype.
>
> Databases seem to differ as to whether the result should be null or
> whether an error is raised. We need to decide this as well.

I would raise an ClassCastException and wrap it with PersistenceException. A null result with false return value would cause endless debugging hours...
>
> I think the above examples illustrate the utility of defining the
> semantics as providing a filtering as well as downcasting semantics
> (i.e., taking the approach of using null semantics).
>
> The Criteria API already provides the Expression method
> <X> Expression<X> as(Class<X> type);
>
> However, note that the definition of this explicitly states: "This
> method does not cause type conversion: the runtime type is not
> changed. Warning: may result in a runtime failure. "
>
>
> Opinions?
>
> thanks,
>
> -Linda

-adam