简体   繁体   中英

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)

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();

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM