Hello:
I'm experimenting with JPQL queries in JBoss Application Server. I'm using Hibernate as the JPA provider. I've one entity class called User, that doesn't keep any relation with other entities. I'm building a simple query that looks like this:
Code:
SELECT user
FROM User user
Doing so, Hibernate generates a single SQL query that retrieves information from the corresponding table at once. That's the behaviour that I expected.
However, if I use this entity object as the argument of the constructor of another object, using the keyword NEW, the fetching mechanism changes a lot:
Code:
SELECT NEW my.package.UserWrapper (user)
FROM User user
In this situation, Hibernate builds a SQL query to get the IDs of all the existing users first. Then it calls another SQL query to retrieve all the field values of the user as many times as IDs have been found. So if there are 100 users in the table, it performs 101 queries.
Obviously this example is just that, an example. I know that the NEW constructor expression is designed to retrieve arbitrary entity fields instead of whole entities. However, sometimes I want to retrieve a whole entity which is going to be updated later (therefore this need), plus a few fields of other related entities, without the need of fetching all the chain of related entities together. Something like this:
Code:
SELECT NEW my.package.UserResult (
user, user.group.role.id, user.region.country.id
FROM User user
Why does it happen?
Thank you!