我使用 Spring 3.1 + Hibernate 4。
我创建了以下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>
如您所见,上面的 sessionFactory
适用于 Hibernate 4。
我正在尝试通过 Java 代码创建一个 HibernateTemplate
(org.springframework.orm.hibernate3.HibernateTemplate
) sessionFactory
,但我不知道如何做到这一点。
我尝试过以下代码:
@Resource(name="sessionFactory")
public void setSessionFactory(LocalSessionFactoryBean sessionFactory) {
this.hibernateTemplate = new HibernateTemplate(sessionFactory.getObject());
}
但我收到以下错误消息:
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]
你能展示一下如何做到这一点吗?
最佳答案
自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...
来自包org.springframework.orm.hibernate4的javadoc:
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.
关于spring - 通过 org.springframework.orm.hibernate4.LocalSessionFactoryBean 创建 HibernateTemplate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9780585/