views:

422

answers:

2

I have an entity A that has a foreign key of entity B:

entity A --> id, entity_a_name, foreign_key_entity_B

When I call

return session.createCriteria(EntityA.class).list();

I get the property of entityB inside entity A as well. How do I make it lazy load so it will not load enityB if not needed?

+1  A: 

It's unclear from your description what type of relationship you are talking about, but if it is Many-to-One or One-to-One, things aren't so straightforward. If A.entityB is nullable (non-optional) then Hibernate is forced to eager-load the relationship in order to see if the property is null. Only by marking the relationship as non-optional (in which case Hibernate assumes that it isn't null since it is an error otherwise) can you make it load lazily.

Adam Batkin
+1  A: 
  • @LazyCollection: defines the lazyness option on @ManyToMany and @OneToMany associations. LazyCollectionOption can be TRUE (the collection is lazy and will be loaded when its state is accessed), EXTRA (the collection is lazy and all operations will try to avoid the collection loading, this is especially useful for huge collections when loading all the elements is not necessary) and FALSE (association not lazy)

  • @Fetch: defines the fetching strategy used to load the association. FetchMode can be SELECT (a select is triggered when the association needs to be loaded), SUBSELECT (only available for collections, use a subselect strategy - please refer to the Hibernate Reference Documentation for more information) or JOIN (use a SQL JOIN to load the association while loading the owner entity). JOIN overrides any lazy attribute (an as sociation loaded through a JOIN strategy cannot be lazy).

Tim