Considering the following “model”:
USER
Long: PK
String: firstName
String: lastName
USER_EXT
Long: PK
String: moreInfo
Date: lastModified
I’m trying to find/create the correct Hibernate mapping (using Annotations) such that, with an HQL query as simple as “from User”, it would generate the following SQL:
select firstName, moreInfo from USER, USER_EXT where user.pk = user_ext.pk
I’ve tried everything, from using @Secondarytable to @OneToOne association, but I can’t make it work.
The best result I have now is with the @OneToOne association which generate multiple SQL queries, one to fetch rows in USER and for each rows in the resultset a select query from USER_EXT.
This is quite ineffective.
Any idea ?
Choosing between
OneToOneandSecondarytablesomehow depends on the object model (i.e. if you want an entity for the user extension). I chose to use aOneToOneassociation and two entities.For the
User(note the use of thePrimaryKeyJoinColumnfor the shared primary key):And the
UserExt:With the above entities, the following HQL query:
Generates the following SQL query:
Which is the expected result.
PS: JPA 1.0 actually provides poor support of derived identifiers (things are much better in JPA 2.0) and you will have to set the
Idmanually on theUserExt, unless you use an Hibernate specificforeigngenerator. See the question below for details.Related Question