seesee
seesee

Reputation: 1155

Hibernate Lazy Loading and initialization

I'm attempting to lazy initialize my one to many relationship using Spring's Hibernate Template.

I have read the following guide. http://dinukaroshan.blogspot.sg/2012/08/lazyeager-loading-using-hibernate-by.html

with the reference to these codes

/** 
  * {@inheritDoc} 
  */  
 public Child getChildByIdWithoutToys(Long childId) {  
  return getHibernateTemplate().get(Child.class, childId);  
 }  

 /** 
  * {@inheritDoc} 
  */  
 public Child getChildByIdWithToys(Long childId) {  
  Child child = getChildByIdWithoutToys(childId);  
  /** 

The above code uses 2 session and 2 sql statement(expose sql)

Is there a way to perform this in one session and one sql statement(hibernate_showsql=true)

Upvotes: 0

Views: 265

Answers (2)

Luca Basso Ricci
Luca Basso Ricci

Reputation: 18403

Before all, this is a quirk and dirty solution applied to example you posted in question, not the best pratice.
You can perform this code with 1 session and 2 sql (less is impossibile because your are executing two separate instruction).
In short, you have to get your sessionFactory from spring-context, open a session, do your code and close session; transaction are directly managed by spring! in your main do:

/*...object creation... */
final SessionFactory sf = context.getBean("sessionFactory");
/* Session creation */
final Session s = sf.openSession();
ChildDAO childDAO = (ChildDAO) context.getBean("childDAO");

childDAO.persistChild(child);
/*other code*/
/* session close */
s.close();

Upvotes: 1

In order to keep everything in one session, you need to be calling these methods from within one. The easiest way to do this is to use Spring's declarative transaction support, preferably by marking the top-level methods (where you might enter the overall persistence system) with @Transactional. These lookup methods will "inherit" the transaction from their callers instead of creating new ones.

Upvotes: 0

Related Questions