Java Reference
In-Depth Information
Using Hibernate detached objects
The HibernateOrderAttachmentManager does not need to detach orders, but it does
need to make sure they are loaded. Here is HibernateOrderAttachmentManager , which
calls HibernateTemplate.initialize() to ensure that the required objects are loaded
and calls HibernateTemplate.update() to reattach the order:
public class HibernateOrderAttachmentManager extends
HibernateDaoSupport implements OrderAttachmentManager {
public HibernateOrderAttachmentManager(
HibernateTemplate hibernateTemplate) {
setHibernateTemplate(hibernateTemplate);
}
public Order detach(Order order) {
HibernateTemplate template = getHibernateTemplate();
template.initialize(order);
template.initialize(order.getLineItems());
for (Iterator it = order.getLineItems().iterator();
it.hasNext();){
OrderLineItem lineItem = (OrderLineItem) it.next();
MenuItem menuItem = lineItem.getMenuItem();
template.initialize(menuItem);
}
return order;
}
public Order attach(Order order) {
getHibernateTemplate().update(order);
return order;
}
}
Because the Hibernate objects are automatically detached when the session is
closed, the detach() method just calls HibernateTemplate.initialize() to
ensure that the order, its line items, and their menu items are loaded. An alterna-
tive approach would be for the AcknowledgeOrderService to load the order by
executing a query that uses fetch joins to eagerly load the objects. This simplifies
the code by eliminating the need to call HibernateTemplate.initialize() and
would improve performance by reducing the number of database accesses. How-
ever, because a Hibernate application cannot always eagerly load all of the objects
that it must return to the presentation tier, it is worthwhile looking at an example
that uses Hibernate.initialize() .
The attach() method calls HibernateTemplate.update() to attach the order.
This method reassociates the order with the Session , which does not involve any
 
Search WWH ::




Custom Search