gpt4 book ai didi

java - Spring org.apache.openjpa.persistence.InvalidStateException : you cannot access the EntityTransaction when using managed transactions

转载 作者:行者123 更新时间:2023-11-30 11:18:45 24 4
gpt4 key购买 nike

我正在尝试使用 spring、jpa 2.0 和带注释的 PersistenceContext EntityManager 进行简单的容器管理事务。

下面是我的 app-context.xml(spring 配置):

<beans ...>

<context:annotation-config />

<context:component-scan base-package="com.example.test.config" />
<context:component-scan base-package="com.example.test.controllers" />
<context:component-scan base-package="com.example.test.services" />

<jee:jndi-lookup id="myDS" jndi-name="jdbc/myDS" expected-type="javax.sql.DataSource" />

<bean id="myEMF" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="testPU"/>
<property name="packagesToScan" value="com.example.test.model"/>
<property name="jtaDataSource" ref="saturnDS"/>
<property name="mappingResources" value="META-INF/orm.xml" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.OpenJpaVendorAdapter" />
</property>
</bean>

<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="myEMF" />
<property name="dataSource" ref="myDS" />
</bean>

<tx:annotation-driven transaction-manager="txManager"/>

</beans>

我在 com.example.test.services 中有一个名为 MyServiceImpl 的服务:

@Repository("myService")
@Transactional
public class MyServiceImpl implements MyService{

@PersistenceContext(unitName = "testPU")
@Qualifier("myEMF")
private EntityManager em;

@Override
public String getMessage() {
return "Hello, World!";
}

@Override
public Customer getFirstCustomer() {
CustomerId id = new CustomerId();
id.setId(new BigInteger("1"));
id.setStartVersion(1);
return em.find(Customer.class, id); // it uses a composite key
}
}

当我尝试使用注入(inject)到 mvc Controller 中的 bean 调用 getFirstCustomer() 方法时出现以下错误(为简洁起见未显示):

更新:这里是完整的堆栈跟踪:

    [14/05/14 11:01:20:812 EST] 0000008f webapp        E com.ibm.ws.webcontainer.webapp.WebApp logServletError SRVE0293E: [Servlet Error]-[DispatcherServlet]: org.springframework.transaction.CannotCreateTransactionException: Could not open JPA EntityManager for transaction; nested exception is <openjpa-2.2.2-SNAPSHOT-r422266:1462076 nonfatal user error> org.apache.openjpa.persistence.InvalidStateException: You cannot access the EntityTransaction when using managed transactions.
at org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:430)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.getTransaction(AbstractPlatformTransactionManager.java:373)
at org.springframework.transaction.interceptor.TransactionAspectSupport.createTransactionIfNecessary(TransactionAspectSupport.java:420)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:257)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy525.getMessage(Unknown Source)
at com.example.test.controllers.IndexController.showIndex(IndexController.java:23)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:88)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
at java.lang.reflect.Method.invoke(Method.java:613)
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:749)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:689)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:83)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:938)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:870)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:961)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:852)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:575)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:837)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1227)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:776)
at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:458)
at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1032)
at com.ibm.ws.webcontainer.webapp.WebApp.handleRequest(WebApp.java:3761)
at com.ibm.ws.webcontainer.webapp.WebGroup.handleRequest(WebGroup.java:304)
at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:976)
at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1662)
at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:200)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:459)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:526)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:312)
at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.ready(HttpInboundLink.java:283)
at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.sendToDiscriminators(NewConnectionInitialReadCallback.java:214)
at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.complete(NewConnectionInitialReadCallback.java:113)
at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:175)
at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1862)
Caused by: <openjpa-2.2.2-SNAPSHOT-r422266:1462076 nonfatal user error> org.apache.openjpa.persistence.InvalidStateException: You cannot access the EntityTransaction when using managed transactions.
at org.apache.openjpa.persistence.EntityManagerImpl.getTransaction(EntityManagerImpl.java:552)
at org.apache.openjpa.persistence.EntityManagerImpl.getTransaction(EntityManagerImpl.java:102)
at org.springframework.orm.jpa.DefaultJpaDialect.beginTransaction(DefaultJpaDialect.java:67)
at org.springframework.orm.jpa.vendor.OpenJpaDialect.beginTransaction(OpenJpaDialect.java:50)
at org.springframework.orm.jpa.JpaTransactionManager.doBegin(JpaTransactionManager.java:380)
... 49 more

我正在使用 WebSphere v8.5.5.0 和 Spring 4.0.4

如果这是我应该知道的基础知识,请原谅我,我只希望注入(inject)的 EntityManager 对我的交易目的有效。

更新:因为我使用的是 websphere,所以我需要一个从容器中获取的 transactionManager。我已将我的 transactionManager 引用换成以下内容:

<tx:annotation-driven />
<bean id="transactionManager" class="org.springframework.transaction.jta.WebSphereUowTransactionManager" />

但是现在应用程序提示说 Customer 类没有得到增强,而它肯定在 EMF 的“packagesToScan 属性中”。

更新:这是我的实体类:(注意我使用的是 lombok,它为我生成样板文件。

package com.example.test.model;
import ...;
@Entity
@Getter
@Setter
@Table(name = Rep.TABLE_NAME)
@IdClass(CustomerId.class)
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@EqualsAndHashCode
public class Customer implements Serializable {

public static final String TABLE_NAME = "Customer";
public static final String ID_COLUMN = "CUSTOMERID";
public static final String START_VERSION_COLUMN = "STARTVERSION";
/* etc */

@Id
@Column(name = ID_COLUMN, nullable = false, insertable = true, updatable = true, precision = 0)
private BigInteger id;

@Id
@Column(name = START_VERSION_COLUMN, nullable = false, insertable = true, updatable = true)
private int startVersion;

/* etc ad. nauseum */

}

最佳答案

我已经找到了解决方案,在研究答案的过程中我学到了一些东西。

首先,因为我使用的是 Websphere,事务管理器已经由容器提供。这可以像这样在我的配置中声明为一个 bean:

<tx:annotation-driven />
<bean id="transactionManager" class="org.springframework.transaction.jta.WebSphereUowTransactionManager" />

transactionManager<tx:annotation-driven /> 的默认名称标记寻找初始化它的事务管理器(否则由 transaction-manager 属性指定。

其次,spring容器不会在运行时自动转换实体类,要指定这个需求就意味着要加一个LoadTimeWeaverLocalContainerEntityManagerFactoryBean声明:

<bean id="myEMF" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="loadTimeWeaver">
<!-- Spring provides a websphere compatible load time weaver -->
<bean class="org.springframework.instrument.classloading.websphere.WebSphereLoadTimeWeaver" />
</property>
....
</bean>

现在这两个元素都已到位,该函数从方法调用中优雅地返回所需的 Customer 对象 :)

关于java - Spring org.apache.openjpa.persistence.InvalidStateException : you cannot access the EntityTransaction when using managed transactions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23644216/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com