Spring中No EntityManager with actual transaction available错误解决
技术背景
在Spring MVC Web应用程序中,当尝试调用persist
方法将实体模型保存到数据库时,可能会遇到No EntityManager with actual transaction available for current thread - cannot reliably process 'persist' call
错误。此错误通常表示当前线程没有可用的实际事务,无法可靠地处理持久化调用。
实现步骤
1. 检查配置文件
确保dispatcher-servlet.xml
等配置文件中正确配置了EntityManagerFactory
和TransactionManager
。示例配置如下:
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceXmlLocation" value="classpath:./META-INF/persistence.xml" />
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="databasePlatform" value="org.hibernate.dialect.H2Dialect" />
<property name="showSql" value="true" />
<property name="generateDdl" value="false" />
</bean>
</property>
<property name=