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!

1 Kommentar:

Hamlet D'Arcy hat gesagt…

Thanks for the tip!

By the way, I run a user group up in Basel and if you know anyone that might be interested then check us out at "hackergarten.net". Especially if there is anyone interested in Groovy down in Bern then please send them our way!