Note that you shouldn't log HibernateExceptions as warnings: Better convert them to Spring's unchecked DataAccessException hierarchy, for example via
Code:
throw SessionFactoryUtils.convertHibernateAccessExcepton(he);
If you derive from HibernateDaoSupport, you can even simplify that by access the base class' convenience methods. I've also streamlined the rest of the code a bit.
Code:
public List getProductList() {
Session session = null;
try {
session = [i]getSession(true)[/i];
Criteria criteria = session.createCriteria(Product.class);
//criteria.addOrder(Order.asc("title"));
return criteria.list();
}
catch (HibernateException he) {
throw [i]convertHibernateAccessException(he)[/i];
}
finally {
[i]closeSessionIfNecessary(session)[/i];
}
}
Alternatively, you could implement that as HibernateCallback. This results in significantly shorter code, as the template will care for Session opening and closing and for conversion of HibernateExceptions to Spring's DataAccessException hierarchy.
Code:
public List getProductList() {
return getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException {
Criteria criteria = session.createCriteria(Product.class);
//criteria.addOrder(Order.asc("title"));
return criteria.list();
});
}
Even simpler than that, try to leverage HibernateTemplate's operation methods as far as possible. Those methods provide an extensive set of typical operations, with full resource and exception management. For example, to retrieve all Products:
Code:
public List getProductList() {
return getHibernateTemplate().loadAll(Product.class);
}
For sorting by title, you could use "find" with a corresponding HQL query. HQL lends itself very nicely for one-line operation objects. Of course, if you prefer the Criteria API, you can still use that (see above).
Code:
public List getProductList() {
return getHibernateTemplate().find("from Product order by title asc");
}
Juergen