views:

1830

answers:

1

In SQL it is easy to do a join and only return the columns you want from the joined table. What is the best way to map this in JPA / Hibernate?

For example, there is a Folder entity mapped to the EMAIL_FOLDER and an Email entity mapped to the EMAIL table. There is a one-to-many relationship from Folder to Email. The Email entity is rather heavy because it contains CLOBs of the text, attachments, etc. There are some cases where we need to get the whole Email back and there are other cases when we just want to bring back senderName, subject, and sentDate and do not want the memory overhead of bringing in the CLOB data. Accomplishing this in SQL is straightforward, but I'm not sure what the best approach would be in JPA / Hibernate.

I'm thinking about creating a LightEmail that only maps to senderName, subject, and sentDate. Is this the best way to handle something like this?

Update: At this point I'd like to avoid byte code instrumentation if possible.

+1  A: 

Annotate the property (the CLOB) as @Basic(fetch=FetchType.LAZY)

See Declaring basic property mappings in the Hibernate Reference

Ken Gentle
The documentation says "Lazy property loading requires buildtime bytecode instrumentation! If your persistent classes are not enhanced, Hibernate will silently ignore lazy property settings and fall back to immediate fetching."
Paul Croarkin
It then goes on to say "A different (better?) way to avoid unnecessary column reads, at least for read-only transactions is to use the projection features of HQL or Criteria queries. This avoids the need for buildtime bytecode processing and is certainly a preferred solution."
Paul Croarkin

related questions