You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决Spring整合Hibernate后方法无法生效的问题

Spring整合Hibernate项目无报错但持久化操作不生效排查

问题场景

使用Spring搭建Hibernate项目,运行时无任何错误或警告,但所有Hibernate方法(如save)均无法将数据写入数据库。以下是项目代码与配置文件:

实体类:Student.java

public class Student {

    private long id;
    private String name;
    private String dept;
    //getters and setters
}

DAO类:StudentDao.java

public class StudentDao{

    HibernateTemplate template;

    public void setTemplate(HibernateTemplate template) {
        this.template = template;
    }

    public void saveStudent(Student s){
        template.save(s);
    }

}

主类:Main.java

public class Main {
    public static void main(String[] args) {

        ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
        StudentDao studentDao = (StudentDao) ctx.getBean("st");

        Student s=new Student();
        s.setId(5);
        s.setName("Messi");
        s.setDept("Physics");
        studentDao.saveStudent(s);
        System.out.println(" Successfully persisted the student. Please check your database for results.");

    }
}

配置文件:applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    <bean id="ds" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.postgresql.Driver" />
        <property name="url" value="jdbc:postgresql://localhost:5432/postgres" />
        <property name="username" value="postgres" />
        <property name="password" value="***" />

    </bean>

    <bean id="localSessionFactory"  class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="ds"></property>
        <property name="mappingResources">
            <list>
                <value>student.hbm.xml</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQL10Dialect</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="connection.autocommit">true</prop>
            </props>
        </property>
    </bean>
    <bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
        <property name="sessionFactory" ref="localSessionFactory"></property>
        <property name="checkWriteOperations" value="false"></property>
    </bean>
    <bean id="st" class="example.StudentDao">
        <property name="template" ref="hibernateTemplate"></property>
    </bean>
</beans>

Hibernate映射文件:student.hbm.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="example.Student" table="student">
        <id name="id">
            <generator class="assigned"></generator>
        </id>
        <property name="name"></property>
        <property name="dept"></property>
    </class>
</hibernate-mapping>

问题排查与解决方案

1. 事务管理缺失(核心问题)

当前配置中没有配置Spring事务管理器,Hibernate的save操作需要事务支持才能完成持久化。即使设置了connection.autocommit=true,Spring整合Hibernate时,HibernateTemplate默认会绑定事务上下文,缺失事务配置会导致操作无法提交到数据库。

解决步骤:

在applicationContext.xml中添加事务管理器配置,并开启事务注解支持:

<!-- 添加tx命名空间到beans标签 -->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/tx
   http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

<!-- 配置Hibernate事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
    <property name="sessionFactory" ref="localSessionFactory"/>
</bean>

<!-- 开启事务注解支持 -->
<tx:annotation-driven transaction-manager="transactionManager"/>

然后在StudentDao的saveStudent方法上添加@Transactional注解:

import org.springframework.transaction.annotation.Transactional;

public class StudentDao{

    HibernateTemplate template;

    public void setTemplate(HibernateTemplate template) {
        this.template = template;
    }

    @Transactional
    public void saveStudent(Student s){
        template.save(s);
    }

}

2. 调整connection.autocommit配置

移除hibernateProperties中的connection.autocommit=true配置,由Spring事务管理器统一处理事务提交,避免配置冲突。

3. 恢复checkWriteOperations默认值

将hibernateTemplate的checkWriteOperations改回默认值true,这样在无事务时会抛出明确异常,便于快速定位问题:

<bean id="hibernateTemplate" class="org.springframework.orm.hibernate5.HibernateTemplate">
    <property name="sessionFactory" ref="localSessionFactory"></property>
    <!-- 移除或注释该行,恢复默认值true -->
    <!-- <property name="checkWriteOperations" value="false"></property> -->
</bean>

4. 基础验证

  • 确认数据库URL、用户名、密码正确,应用能正常连接PostgreSQL。
  • 检查postgres用户对student表的插入权限。
  • 查看数据库中是否存在student表,验证hibernate.hbm2ddl.auto=update是否生效。

总结

最核心的问题是缺少Spring事务管理器配置,导致Hibernate写操作无法提交到数据库。添加事务管理器并启用事务注解后,持久化操作即可正常生效。

内容的提问来源于stack exchange,提问作者darknight

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 07:29:54