Skip to content

Instantly share code, notes, and snippets.

@kdmukai
Created November 4, 2011 18:06
Show Gist options
  • Save kdmukai/1340037 to your computer and use it in GitHub Desktop.
Save kdmukai/1340037 to your computer and use it in GitHub Desktop.
_GenericDaoHibernateImpl<T> excerpt with session-safe getHibernateTemplate.save()
import java.lang.reflect.Method;
/**
* Initialize any lazy-loaded member vars of the entity before saving. This is necessary
* because the session that supplies the lazy-loading will not be accessible here in the
* save() call if OpenSessionInView's singleSession=false. It uses one session for read-
* only getters and another for save/updates.
*
**/
@Override
public void save(T entity) {
try {
// Get all the public methods declared in the entity class plus inherited methods
Method methods[] = clazz.getMethods();
for (Method method: methods) {
Package returnTypePackage = method.getReturnType().getPackage();
// Only look at the getters whose return type is an entity object from my
// hibernate-mapped domain.
if (method.getName().startsWith("get") && returnTypePackage != null && returnTypePackage.getName().startsWith("com.essaytagger.model")) {
// Only look at the simple no-arg getters - the goal here is to match the
// corresponding getMyPojo()/setMyPojo(myPojo) where myPojo might not be
// initialized yet.
if (method.toString().contains("()")) {
try {
// Grab the pojo from the getter
Object obj = method.invoke(entity);
// If it isn't yet initialized...
if (obj instanceof HibernateProxy) {
// ...initialize it!
getHibernateTemplate().initialize(obj);
}
} catch (Exception e) {
continue;
}
}
}
}
} catch (Throwable e) {
log.debug(e);
}
// After all that we can now save without worrying about Session conflicts.
getHibernateTemplate().save(entity);
}
Cat oldCat = catDao.get(oldCatId);
Cat newCat = new Cat();
newCat.setName("Whiskers");
newCat.setOwner(oldCat.getOwner());
catDao.save(newCat); // Causes Session conflict because Owner isn't initialized
Cat oldCat = catDao.get(oldCatId);
// Pointless access to force Hibernate to initialize Owner.
oldCat.getOwner().getFirstName();
Cat newCat = new Cat();
newCat.setName("Whiskers");
newCat.setOwner(oldCat.getOwner());
catDao.save(newCat); // Now everything goes smoothly.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment