Proper use of getHibernateTemplate() in Spring MVC app?
I have a bunch of Hibernate mapped objects in my Spring MVC app. Default seems to be lazy loading for nested objects with relations. I realized this by getting a lot of errors in my JSP when accessing e.g. a list of children objects.
So I implemented a second method to get a list of objects with all children initliazed. I was wondering if someone could give me some feedback if this was the way to go or not?
This is my code in my DAO implementation that works:
public List<Address> getTripListFullyInitliazed() {
HibernateTemplate template = getHibernateTemplate();
List<Address> addresses = template.loadAll(Address.class);
for (Address address : address) {
template.initialize(address.getChildren());
}
return addresses;
}
C开发者_开发知识库an someone please tell me if this ok to do or if I should change something?
I think a more elegant approach would be to use HQL JOIN FETCH
clause, since it minimizes the number of SQL queries issued, as well as makes your code more clear:
public List<Address> getTripListFullyInitliazed() {
return getHibernateTemplate().find(
"from Address a left join fetch a.children");
}
See also:
- 16.3. Associations and joins
- 21.1. Fetching strategies
I think the standard solution for this problem is to use OpenSessionInViewFilter
:
Servlet 2.3 Filter that binds a Hibernate
Session
to the thread for the entire processing of the request. Intended for the "Open Session in View" pattern, i.e. to allow for lazy loading in web views despite the original transactions already being completed.This filter makes Hibernate Sessions available via the current thread, which will be autodetected by transaction managers. It is suitable for service layer transactions via
HibernateTransactionManager
orJtaTransactionManager
as well as for non-transactional execution (if configured appropriately).
精彩评论