Spring JPA:没有正在进行的事务
Posted
技术标签:
【中文标题】Spring JPA:没有正在进行的事务【英文标题】:Spring JPA: no transaction is in progress 【发布时间】:2016-03-26 05:05:53 【问题描述】:在我的 Spring 应用程序中持久化实体时遇到问题。只是做em.merge()
完成没有错误但不更新数据库,尝试em.flush()
会导致此异常:
2015-12-19 18:01:40 调试 DispatcherServlet:976 - 无法完成 请求 org.springframework.dao.InvalidDataAccessApiUsageException:否 交易正在进行中;嵌套异常是 javax.persistence.TransactionRequiredException:没有事务在 进展
这是我的配置:
@Configuration
@EnableWebMvc
@ComponentScan
@Import( SecurityConfig.class )
@PropertySource("classpath:application.properties")
@EnableJpaRepositories
@EnableTransactionManagement
public class ApplicationContext extends WebMvcConfigurerAdapter
@Bean
public DataSource dataSource()
DriverManagerDataSource datasource = new DriverManagerDataSource();
datasource.setDriverClassName("org.postgresql.Driver");
datasource.setUrl("jdbc:postgresql://localhost/expert");
datasource.setUsername("expert");
datasource.setPassword("expert");
return datasource;
@Bean
public JdbcTemplate jdbcTemplate()
return new JdbcTemplate(dataSource());
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory()
LocalContainerEntityManagerFactoryBean factoryBean
= new LocalContainerEntityManagerFactoryBean();
factoryBean.setDataSource(dataSource());
factoryBean.setPackagesToScan(new String[ ] "test.model" );
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
factoryBean.setJpaVendorAdapter(vendorAdapter);
factoryBean.setJpaProperties(this.additionalProperties());
return factoryBean;
@Bean
public PlatformTransactionManager transactionManager()
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation()
return new PersistenceExceptionTranslationPostProcessor();
Properties additionalProperties()
Properties properties = new Properties();
properties.setProperty("hibernate.show_sql", "true");
properties.setProperty("hibernate.format_sql", "false");
properties.setProperty("hibernate.hbm2ddl.auto", "update");
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
return properties;
我的服务:
@Service
@Transactional
public class ApiProjectServiceImpl implements ApiProjectService
@Autowired
private ApiProjectRepository apiProjectRepository;
public Project getProject(Integer id)
return apiProjectRepository.getProject(id);
public Project save(Project project) return apiProjectRepository.save(project);
还有存储库:
@Repository
public class ApiProjectRepositoryImpl implements ApiProjectRepository
@PersistenceContext
private EntityManager em;
public Project getProject(Integer id)
Project project = em.createQuery("select p from Project p where id = " + id, Project.class)
.getSingleResult();
return project;
public Project save(Project project)
project = em.merge(project);
em.flush();
return project;
尝试save()
时的堆栈跟踪:
2015-12-19 18:15:05 DEBUG FilterSecurityInterceptor:215 - Authorization successful
2015-12-19 18:15:05 DEBUG FilterSecurityInterceptor:227 - RunAsManager did not change Authentication object
2015-12-19 18:15:05 DEBUG FilterChainProxy:323 - /api/project reached end of additional filter chain; proceeding with original chain
2015-12-19 18:15:05 DEBUG OpenEntityManagerInViewFilter:160 - Opening JPA EntityManager in OpenEntityManagerInViewFilter
2015-12-19 18:15:05 DEBUG DispatcherServlet:823 - DispatcherServlet with name 'dispatcher' processing POST request for [/api/project]
2015-12-19 18:15:05 DEBUG RequestMappingHandlerMapping:229 - Looking up handler method for path /api/project
2015-12-19 18:15:05 DEBUG RequestMappingHandlerMapping:234 - Returning handler method [public test.model.Project test.api.ApiController.saveProject(test.model.Project)]
2015-12-19 18:15:05 DEBUG DefaultListableBeanFactory:246 - Returning cached instance of singleton bean 'apiController'
2015-12-19 18:15:05 DEBUG RequestResponseBodyMethodProcessor:140 - Reading [class test.model.Project] as "application/json;charset=UTF-8" using [org.springframework.http.converter.json.MappingJacksonHttpMessageConverter@71528048]
2015-12-19 18:15:05 DEBUG Loader:2136 - Loading entity: [test.model.Project#16623]
2015-12-19 18:15:05 DEBUG SQL:109 - select project0_.id as id1_6_1_, project0_.awarded as awarded2_6_1_, project0_.broker as broker3_6_1_, project0_.brokerEmail as brokerEm4_6_1_, project0_.brokerPhone as [...]
2015-12-19 18:15:05 DEBUG LogicalConnectionImpl:226 - Obtaining JDBC connection
2015-12-19 18:15:05 DEBUG DriverManagerDataSource:162 - Creating new JDBC DriverManager Connection to [jdbc:postgresql://localhost/expert]
2015-12-19 18:15:05 DEBUG LogicalConnectionImpl:232 - Obtained JDBC connection
2015-12-19 18:15:05 DEBUG Loader:951 - Result set row: 0
2015-12-19 18:15:05 DEBUG Loader:1485 - Result row: null, EntityKey[test.model.Project#16623]
2015-12-19 18:15:05 DEBUG Loader:1336 - Result set contains (possibly empty) collection: [test.model.Project.assignedExperts#16623]
2015-12-19 18:15:05 DEBUG TwoPhaseLoad:160 - Resolving associations for [test.model.Project#16623]
2015-12-19 18:15:05 DEBUG Loader:2136 - Loading entity: [test.model.Company#3]
2015-12-19 18:15:05 DEBUG SQL:109 - select company0_.id as id1_1_0_, company0_.email as email2_1_0_, company0_.name as name3_1_0_ from Company company0_ where company0_.id=?
2015-12-19 18:15:05 DEBUG Loader:951 - Result set row: 0
2015-12-19 18:15:05 DEBUG Loader:1485 - Result row: EntityKey[test.model.Company#3]
2015-12-19 18:15:05 DEBUG TwoPhaseLoad:160 - Resolving associations for [test.model.Company#3]
2015-12-19 18:15:05 DEBUG TwoPhaseLoad:286 - Done materializing entity [test.model.Company#3]
2015-12-19 18:15:05 DEBUG Loader:2160 - Done entity load
2015-12-19 18:15:05 DEBUG TwoPhaseLoad:286 - Done materializing entity [test.model.Project#16623]
2015-12-19 18:15:05 DEBUG CollectionLoadContext:232 - 1 collections were found in result set for role: test.model.Project.assignedExperts
2015-12-19 18:15:05 DEBUG CollectionLoadContext:280 - Collection fully initialized: [test.model.Project.assignedExperts#16623]
2015-12-19 18:15:05 DEBUG CollectionLoadContext:240 - 1 collections initialized for role: test.model.Project.assignedExperts
2015-12-19 18:15:05 DEBUG Loader:2160 - Done entity load
2015-12-19 18:15:05 DEBUG Loader:2136 - Loading entity: [test.model.Logging#35672]
2015-12-19 18:15:05 DEBUG SQL:109 - select logging0_.id as id1_4_0_, logging0_.date as date2_4_0_, logging0_.message as message3_4_0_, logging0_.project_id as project_5_4_0_, logging0_.username as username4_4_0_ from [...]
2015-12-19 18:15:05 DEBUG Loader:951 - Result set row: 0
2015-12-19 18:15:05 DEBUG Loader:1485 - Result row: EntityKey[test.model.Logging#35672]
2015-12-19 18:15:05 DEBUG TwoPhaseLoad:160 - Resolving associations for [test.model.Logging#35672]
2015-12-19 18:15:05 DEBUG TwoPhaseLoad:286 - Done materializing entity [test.model.Logging#35672]
2015-12-19 18:15:05 DEBUG Loader:2160 - Done entity load
2015-12-19 18:15:05 DEBUG Loader:2136 - Loading entity: [test.model.Logging#35673]
2015-12-19 18:15:05 DEBUG SQL:109 - select logging0_.id as id1_4_0_, logging0_.date as date2_4_0_, logging0_.message as message3_4_0_, logging0_.project_id as project_5_4_0_, logging0_.username as username4_4_0_ from [...]
2015-12-19 18:15:05 DEBUG Loader:951 - Result set row: 0
2015-12-19 18:15:05 DEBUG Loader:1485 - Result row: EntityKey[test.model.Logging#35673]
2015-12-19 18:15:05 DEBUG TwoPhaseLoad:160 - Resolving associations for [test.model.Logging#35673]
2015-12-19 18:15:05 DEBUG TwoPhaseLoad:286 - Done materializing entity [test.model.Logging#35673]
2015-12-19 18:15:05 DEBUG Loader:2160 - Done entity load
2015-12-19 18:15:05 DEBUG Loader:2136 - Loading entity: [test.model.Party#4903]
2015-12-19 18:15:05 DEBUG SQL:109 - select party0_.id as id1_5_0_, party0_.addressCity as addressC2_5_0_, party0_.addressStreet as addressS3_5_0_, party0_.addressZip as addressZ4_5_0_, party0_.email as email5_5_0_, party0_.expert as [...]
2015-12-19 18:15:05 DEBUG Loader:951 - Result set row: 0
2015-12-19 18:15:05 DEBUG Loader:1485 - Result row: EntityKey[test.model.Party#4903]
2015-12-19 18:15:05 DEBUG TwoPhaseLoad:160 - Resolving associations for [test.model.Party#4903]
2015-12-19 18:15:05 DEBUG TwoPhaseLoad:286 - Done materializing entity [test.model.Party#4903]
2015-12-19 18:15:05 DEBUG Loader:2160 - Done entity load
2015-12-19 18:15:05 DEBUG ExceptionHandlerExceptionResolver:132 - Resolving exception from handler [public test.model.Project test.api.ApiController.saveProject(test.model.Project)]: org.springframework.dao.InvalidDataAccessApiUsageException: no transaction is in progress; nested exception is javax.persistence.TransactionRequiredException: no transaction is in progress
2015-12-19 18:15:05 DEBUG ResponseStatusExceptionResolver:132 - Resolving exception from handler [public test.model.Project test.api.ApiController.saveProject(test.model.Project)]: org.springframework.dao.InvalidDataAccessApiUsageException: no transaction is in progress; nested exception is javax.persistence.TransactionRequiredException: no transaction is in progress
2015-12-19 18:15:05 DEBUG DefaultHandlerExceptionResolver:132 - Resolving exception from handler [public test.model.Project test.api.ApiController.saveProject(test.model.Project)]: org.springframework.dao.InvalidDataAccessApiUsageException: no transaction is in progress; nested exception is javax.persistence.TransactionRequiredException: no transaction is in progress
2015-12-19 18:15:05 DEBUG DispatcherServlet:976 - Could not complete request
org.springframework.dao.InvalidDataAccessApiUsageException: no transaction is in progress; nested exception is javax.persistence.TransactionRequiredException: no transaction is in progress
at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:413)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:157)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:417)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:58)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:163)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
at com.sun.proxy.$Proxy48.save(Unknown Source)
at test.api.ApiProjectServiceImpl.save(ApiProjectServiceImpl.java:24)
at test.api.ApiController.saveProject(ApiController.java:58)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.method.support.InvocableHandlerMethod.invoke(InvocableHandlerMethod.java:215)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:132)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandleMethod(RequestMappingHandlerAdapter.java:745)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:686)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:80)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:925)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:953)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:855)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:829)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter.doFilterInternal(OpenEntityManagerInViewFilter.java:177)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:118)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:57)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:343)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:260)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:142)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:518)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1091)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:673)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1526)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1482)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: javax.persistence.TransactionRequiredException: no transaction is in progress
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.checkTransactionNeeded(AbstractEntityManagerImpl.java:1171)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:1332)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.orm.jpa.ExtendedEntityManagerCreator$ExtendedEntityManagerInvocationHandler.invoke(ExtendedEntityManagerCreator.java:342)
at com.sun.proxy.$Proxy39.flush(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:262)
at com.sun.proxy.$Proxy39.flush(Unknown Source)
at test.api.ApiProjectRepositoryImpl.save(ApiProjectRepositoryImpl.java:35)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:155)
... 79 more
2015-12-19 18:15:05 DEBUG OpenEntityManagerInViewFilter:185 - Closing JPA EntityManager in OpenEntityManagerInViewFilter
2015-12-19 18:15:05 DEBUG EntityManagerFactoryUtils:435 - Closing JPA EntityManager
2015-12-19 18:15:05 DEBUG LogicalConnectionImpl:246 - Releasing JDBC connection
2015-12-19 18:15:05 DEBUG LogicalConnectionImpl:264 - Released JDBC connection
2015-12-19 18:15:05 DEBUG SecurityContextPersistenceFilter:97 - SecurityContextHolder now cleared, as request processing completed
谢谢!
更新 1 显然问题已通过从 Spring 3.2.8 升级到 Spring 4.2.0 得到解决。我没有对代码进行任何更改,我知道需要一个事务,但服务实现用@Transactional
注释。谢谢大家。
【问题讨论】:
正如 flush() 的 javadocs 所说...仅在事务正在进行时才适用。所以大概你要么没有启动 txn,要么是 JTA 正在其他地方启动 根据文档docs.oracle.com/javaee/7/api/javax/persistence/…合并也需要事务 我还没有对此进行测试,但是您将dataSource
和entityManagerFactory
公开为@Bean
s 看起来很可疑,但是在这些bean 方法中您直接调用其他bean 定义,而不是@987654333 @@他们。
我有同样的异常,除了我可以在堆栈跟踪中看到TransactionInterceptor
。我的问题是我传递给JpaTransactionManager#setEntityManagerFactory
的EntityManagerFactory
实例。为了产生那个异常,我使用了LocalContainerEntityManagerFactoryBean#getNativeEntityManagerFactory
并解决它,我将它更正为LocalContainerEntityManagerFactoryBean#getObject()
。 TBH 很幸运我找到了这个,在完成这个之后我发现整个 JPA / JTA Hibernate / Spring 设置(对于相当特殊的情况)非常令人生畏。
【参考方案1】:
将此添加到您的数据源文件/配置中
hibernate.allow_update_outside_transaction: true
它应该可以工作,但请确保您的生产环境
【讨论】:
【参考方案2】:就像@Neil Stockton 提到的那样,一些EntityManager
函数需要事务才能存在。 see the doc
这里是doc
关于flush
函数:
void flush() 将持久化上下文同步到底层 数据库。抛出:TransactionRequiredException - 如果没有 交易或实体经理未加入 当前事务 PersistenceException - 如果刷新失败
Merge
函数也是如此:
T merge(T entity) 将给定实体的状态合并到 当前的持久性上下文。参数:entity - 实体实例 返回:状态合并到的托管实例抛出: IllegalArgumentException - 如果实例不是实体或者是 已移除实体 TransactionRequiredException - 如果没有 在该容器管理的实体管理器上调用事务时 是 PersistenceContextType.TRANSACTION 类型的
所以基本上你想要的是创建new transaction
或使用exists
之一。由于您使用的是 @EnableTransactionManagement
注释,因此您只需注释您的方法即可
@Transactional(propagation=Propagation.REQUIRED)
public Project save(Project project)
project = em.merge(project);
em.flush();
return project;
更多关于Spring
的交易可以在spring docs找到。更多java中的transactions
可以找到at ibm,强烈推荐。
【讨论】:
我知道需要一个事务,但我已经在服务级别有一个@Transactional
注释。我也尝试将注释添加到存储库方法,但这没有帮助。我显然已经通过从 Spring 3.2.8 升级到 Spring 4.2.0 解决了这个问题。我不确定到底是什么问题。以上是关于Spring JPA:没有正在进行的事务的主要内容,如果未能解决你的问题,请参考以下文章
TransactionRequiredException:Spring Data JPA 没有正在进行的事务
企业分布式微服务云SpringCloud SpringBoot mybatis (十七)Spring Boot中的事务管理