spring - 通过 org.springframework.orm.hibernate4.LocalSessionFactoryBean 创建 HibernateTemplate

标签 spring hibernate datasource

我使用 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/

相关文章:

json - ExtJS 4 Spring 3 文件上传。服务器发送错误响应内容类型

java - 在单个 map 中执行多个任务是好习惯吗

java - 如果在尝试将对象保存在数据库中时由 hibernate 生成 SQL 语法错误,如何解决?

java - Spring Boot获取@Configuration类的环境变量

spring - spring boot 在哪里配置默认的application.properties

java - 是否可以使用 java -cp "jarName.jar"com.hw.Main 运行 spring boot 打包的 jar ?

mysql - 带有连接表的 ManyToOne、oneToMany

java - 如何在 spring-boot 和 postgresql 中使用 postgis 类型地理?

java - Spring 3 JavaConfig - 注入(inject)数据源时出现问题

java - Spring 启动 : How to skip datasource configuration running tests