The following section is from reference document of "Spring Java/J2EE Application Framework 2.0.2"
by Rod Johnson etc. on page 212.
12.2.5. Implementing DAOs based on plain Hibernate3 API
Hibernate 3.0.1 introduced a feature called "contextual Sessions", where Hibernate itself manages one current
Session per transaction. This is roughly equivalent to Spring's synchronization of one Hibernate Session per
transaction. A corresponding DAO implementation looks like as follows, based on the plain Hibernate API:
public class ProductDaoImpl implements ProductDao
{
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sessionFactory)
{
this.sessionFactory = sessionFactory;
}
public Collection loadProductsByCategory(
String category)
{
return this.sessionFactory.getCurrentSession().createQuery("from test.Product product where product.category=?").setParameter(0, category).list();
}
}
This style is very similar to what you will find in the Hibernate reference documentation and examples, except
for holding the SessionFactory in an instance variable. We strongly recommend such an instance-based setup
over the old-school static HibernateUtil class from Hibernate's CaveatEmptor sample application. (In
general, do not keep any resources in static variables unless absolutely necessary.)
The above DAO follows the Dependency Injection
pattern: it fits nicely into a Spring IoC container, just like it
would if coded against Spring's HibernateTemplate. Of course, such a DAO can also be set up in plain
Java (for example, in
unit tests): simply instantiate it and call setSessionFactory(..) with the desired factory
reference. As a Spring bean definition, it would look as follows:
<beans>
<bean id="myProductDao" class="product.ProductDaoImpl">
<property name="sessionFactory" ref="mySessionFactory"/>
</bean>
</beans>
<b>
The main advantage of this DAO style is that it depends on Hibernate API only;
no import of any Spring class is required.
</b>
...
My question is how to configure sessionFactory in applicationcontext.xml.
I know the sessionFactory is the type of "org.hibernate.SessionFactory",
not "org.springframework.orm.hibernate3.LocalSessionFactoryBean". The reference
document is not clear on this.