From the HibernateTemplate docs:
Furthermore, some operations just make sense within transactions, for example: contains, evict, lock, flush, clear.
By default HibernateTemplate will use the same existing transaction for all the operations. That means that while in a transaction you can call HibernateTemplate.initialize at any point and it will work. Or HibernateTemplate.lock + HibernateTemplate.initialize if the master record was loaded in a different transaction.
The way to implement an 'initialize' method that works outside of transactions in a HibernateDaoSupport's subclass is this:
Code:
public <E> E initialize(final Object parent, final E proxy) {
return getHibernateTemplate().executeWithNativeSession(new HibernateCallback<E>() {
public E doInHibernate(Session session) throws HibernateException {
session.lock(parent, LockMode.NONE);
Hibernate.initialize(proxy);
return proxy;
}
});
}
That way you can do this:
Code:
List<Order> orders = myDao.getPendingOrders();
for(Order order: orders) {
Set<OrderLines> lines = myDao.initialize(order, order.getOrderLines());
if (lines.size() > 0) {
Customer c = myDao.initialize(order, order.getCustomer());
// Send mail to customer
sendPendingNotificationMail(c.getEmail());
}
}