02 Juni 2009

JPA Constructor Expression Quiz

Assume the following query with constructor expression:

SELECT NEW jpa.to.ContainerTO(p, e.name) FROM Employee e JOIN e.phones p

Question: What is the Type of p in the constructor expression?

1. Collection of Phone
2. Object
3. Phone
4. none of the above

The correct answer is 3!

I would like a collection of Phone because that's what I expected and what the navigation to e.phones tells me. But in reality it returns a cartesian product of Employee and Phone which means that I have to care myself.

I asked Mike Keith and here's his answer:

The spec defines identification variables such that they represent instances, not collections.
When you alias a JOIN the alias represents each instance of the collection, so in your example "p" represents each phone in the collection (for each row in the cartesian product).

There is a section in Chapter 4 in the spec on "Identification Variables" that explains this if you like going to the spec for reference.

Thanks a lot to Mike for his clarification!