请考虑以下代码:
class ClassOne {
@Autowired
ClassTwo classTwo;
public void mainMethod() {
Query query = em.createNativeQuery(...);
classTwo.runTransaction(query);
}
}
@Component
class ClassTwo {
@Transactional
public void runTransaction(Query) {
System.err.println(TransactionSynchronizationManager.isActualTransactionActive());
query.executeUpdate();
}
}
运行mainMethod
时,我遇到以下异常:
Executing an update/delete query javax.persistence.TransactionRequiredException: Executing an update/delete query
at org.hibernate.jpa.spi.AbstractQueryImpl.executeUpdate(AbstractQueryImpl.java:71)
at sun.reflect.GeneratedMethodAccessor103.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.springframework.orm.jpa.SharedEntityManagerCreator$DeferredQueryInvocationHandler.invoke(SharedEntityManagerCreator.java:310)
at $Proxy55.executeUpdate(Unknown Source)
at ...ClassTwo.runTransaction(...)
at net.sf.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.Cglib2AopProxy$CglibMethodInvocation.invokeJoinpoint(Cglib2AopProxy.java:689)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:622)
at ...ClassOne.mainMethod(...)
我觉得奇怪的是,即使您可以在堆栈跟踪中清楚地看到它通过TransactionInterceptor
,它也会记录丢失的事务。
此外isActualTransactionAlive
返回true。
答案 0 :(得分:2)
您需要在事务上下文中获取Query对象。目前,它的外部交易背景。它会解决你的问题。