问题
I work with Spring 3.1 + Hibernate 4.
I've created the following sessionFactory
:
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="myDataSource" />
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.hbm2ddl.auto">validate</prop>
</props>
</property>
<property name="packagesToScan" value="com.my.company"/>
</bean>
As you see, the above sessionFactory
is for Hibernate 4.
I am trying to crate a HibernateTemplate
(org.springframework.orm.hibernate3.HibernateTemplate
) through Java code, by that sessionFactory
, but I am not sure how to do this.
I've tried the following code:
@Resource(name="sessionFactory")
public void setSessionFactory(LocalSessionFactoryBean sessionFactory) {
this.hibernateTemplate = new HibernateTemplate(sessionFactory.getObject());
}
But I'm getting the following error message:
org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'sessionFactory' must be of type [org.springframework.orm.hibernate4.LocalSessionFactoryBean], but was actually of type [org.hibernate.internal.SessionFactoryImpl]
Could you show how to do this?
回答1:
As from this post:
HibernateTemplate isn't recommended for use anymore (about since the release of hibernate 3.0.1) there is no more added value so that isn't going to be in there anymore for hibernate 4. Simply use the plain SessionFactory and use the getCurrentSession method to obtain the current transactional session (don't use openSession!!!!) and you are good to go...
From the javadoc of package org.springframework.orm.hibernate4:
Contains an implementation of Spring's transaction SPI for local Hibernate transactions. This package is intentionally rather minimal, with no template classes or the like, in order to follow native Hibernate recommendations as closely as possible.
回答2:
You don,t need to extends any hibernate dao support class in latest version of spring. You can directly inject hibernate sessionfactory from xml/java based configuration. And it also need to be injected into transaction manger. Refer this link for better understanding: http://hantsy.blogspot.in/2013/07/use-native-hibernate-4-api.html
来源:https://stackoverflow.com/questions/9780585/creating-hibernatetemplate-by-org-springframework-orm-hibernate4-localsessionfac