Sunday, October 30, 2011

JPA @Lob lazy loading

Suppose you have an Entity with (amongst others) a Lob field. How can you make sure the lob field is lazily loaded when your query returns a list of entity instances and you're only interrested in the other columns?
The first thing that comes to mind is instructing JPA to lazy load the field like this:
@Basic(FetchType.Lazy)
@Lob
byte[] attachment;

The problem with this is that in order to work the persistence provider needs to support it. When using Hibernate as JPA provider you have to instrument the bytecode at compile time.

What are the alternatives?

  • Create a separate Entity class containing all fields except the lob field and use this for the collection query.
  • Use a query with a projection to only include the non-lob fields

No comments: