gpt4 book ai didi

java - Web 中 OpenJPA 错误的原因 - 使用托管事务时无法访问 EntityTransaction

转载 作者:行者123 更新时间:2023-12-01 11:07:23 26 4
gpt4 key购买 nike

目标

确认原因是因为尝试在Web容器中使用Container Managed Transaction,并检查我的理解是否正确。

(在下面的示例代码中,实体管理器(非线程安全)被注入(inject)到 servlet 实例变量中,这将导致多线程问题,但这是为了测试目的)

问题

尝试将developerWorks 示例移植到IBM WAS 中。尝试使用实体管理器 em 并使用 em.getTransaction().begin() 启动事务并收到错误。

[27/09/15 0:28:33:717 AEST] 00000090 SystemErr     
R <openjpa-2.2.3-SNAPSHOT-r422266:1686911 nonfatal user error>
org.apache.openjpa.persistence.InvalidStateException:
You cannot access the EntityTransaction when using managed transactions.

[27/09/15 0:28:33:719 AEST] 00000090 SystemErr R at org.apache.openjpa.persistence.EntityManagerImpl.getTransaction(EntityManagerImpl.java:552)
[27/09/15 0:28:33:719 AEST] 00000090 SystemErr R at org.apache.openjpa.persistence.EntityManagerImpl.getTransaction(EntityManagerImpl.java:102)
[27/09/15 0:28:33:720 AEST] 00000090 SystemErr R at com.ibm.ws.jpa.management.JPAExEmInvocation.getTransaction(JPAExEmInvocation.java:263)
[27/09/15 0:28:33:720 AEST] 00000090 SystemErr R at com.ibm.ws.jpa.management.JPAEntityManager.getTransaction(JPAEntityManager.java:421)
[27/09/15 0:28:33:721 AEST] 00000090 SystemErr R at sample.jpa.servlet.CreateAccount.doPost(CreateAccount.java:35)
[27/09/15 0:28:33:721 AEST] 00000090 SystemErr R at javax.servlet.http.HttpServlet.service(HttpServlet.java:595)
[27/09/15 0:28:33:722 AEST] 00000090 SystemErr R at javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
[27/09/15 0:28:33:722 AEST] 00000090 SystemErr R at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1232)
[27/09/15 0:28:33:722 AEST] 00000090 SystemErr R at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:781)
[27/09/15 0:28:33:724 AEST] 00000090 SystemErr R at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:480)
[27/09/15 0:28:33:725 AEST] 00000090 SystemErr R at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
[27/09/15 0:28:33:725 AEST] 00000090 SystemErr R at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1114)
[27/09/15 0:28:33:726 AEST] 00000090 SystemErr R at com.ibm.ws.webcontainer.servlet.CacheServletWrapper.handleRequest(CacheServletWrapper.java:87)
[27/09/15 0:28:33:726 AEST] 00000090 SystemErr R at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:940)
[27/09/15 0:28:33:727 AEST] 00000090 SystemErr R at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1817)
[27/09/15 0:28:33:727 AEST] 00000090 SystemErr R at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:200)
[27/09/15 0:28:33:728 AEST] 00000090 SystemErr R at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:463)
[27/09/15 0:28:33:728 AEST] 00000090 SystemErr R at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:530)
[27/09/15 0:28:33:729 AEST] 00000090 SystemErr R at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:316)
[27/09/15 0:28:33:729 AEST] 00000090 SystemErr R at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.ready(HttpInboundLink.java:287)
[27/09/15 0:28:33:729 AEST] 00000090 SystemErr R at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.sendToDiscriminators(NewConnectionInitialReadCallback.java:214)
[27/09/15 0:28:33:730 AEST] 00000090 SystemErr R at com.ibm.ws.tcp.channel.impl.NewConnectionInitialReadCallback.complete(NewConnectionInitialReadCallback.java:113)
[27/09/15 0:28:33:730 AEST] 00000090 SystemErr R at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:175)
[27/09/15 0:28:33:731 AEST] 00000090 SystemErr R at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
[27/09/15 0:28:33:731 AEST] 00000090 SystemErr R at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
[27/09/15 0:28:33:732 AEST] 00000090 SystemErr R at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
[27/09/15 0:28:33:732 AEST] 00000090 SystemErr R at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
[27/09/15 0:28:33:732 AEST] 00000090 SystemErr R at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
[27/09/15 0:28:33:733 AEST] 00000090 SystemErr R at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
[27/09/15 0:28:33:733 AEST] 00000090 SystemErr R at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1881)

持久性.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="DB2AccountUnit" transaction-type="JTA">
<jta-data-source>jdbc/DB2</jta-data-source>
<class>sample.jpa.Db2account</class>
<properties>
<property name="openjpa.Log" value="File=C:/opt/openjpa/org.apache.openjpa.log, DefaultLevel=INFO, Runtime=TRACE, Tool=INFO, SQL=TRACE, JDBC=TRACE" />
<property name="openjpa.ConnectionUserName" value="User" />
<property name="openjpa.ConnectionPassword" value="Password" />
</properties>
</persistence-unit>
</persistence>

代码

package sample.jpa.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;

import javax.persistence.PersistenceContext;
import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;
import javax.transaction.SystemException;
import javax.naming.InitialContext;

import sample.jpa.AccountException;
import sample.jpa.Db2account;

@WebServlet("/CreateAccount")
public class CreateAccount extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
private static final long serialVersionUID = 1L;

@PersistenceContext(unitName="DB2AccountUnit")
EntityManager em;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}

synchronized protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
InitialContext context = null;
UserTransaction ut = null;

try {
em.getTransaction().begin(); // <---- Error

long accno = Long.parseLong(request.getParameter("ACCNO"));
Db2account account1 = em.find(Db2account.class, accno);

if (account1 != null) {
throw new AccountException("Error : sample.jpa.servlet.CreateAccount : Account Number already exists:" + accno);
} else {
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
java.sql.Date dbDate = new java.sql.Date(format.parse(request.getParameter("DOP"), new ParsePosition(0)).getTime());

Db2account account = new Db2account();
account.setOwner(request.getParameter("OWNERNAME"));
account.setAccno(accno);
account.setAccountType(request.getParameter("ACCOUNTTYPE"));
account.setBalance(new BigDecimal(request.getParameter("BALANCE")));
account.setDateOpen(dbDate);

em.persist(account);
em.getTransaction().commit();

response.sendRedirect("Create_Account.jsp");
}
} catch (Exception e) {
e.printStackTrace();
em.getTransaction().rollback();
try{
ut.rollback();
} catch (SystemException se){
se.printStackTrace();
printMessage(se, response.getWriter());
}
}
}
}

问题

(更新:发现理解完全错误。自行回答)

请告知我的以下理解是否正确。

我的理解是,该错误是因为 EntityManager.getTransaction() 提供的 EntityTransaction 将用作 EJB 容器中的容器管理事务 (CMT),而不是 Web 容器中。

Web容器(我相信一般情况下)不支持CMT,因此导致了错误。消息“您在使用托管事务时无法访问 EntityTransaction”意味着“您无法在需要使用 Bean Managed Transacdtion 和 javax.transaction.UserTransaction 的地方使用 CMT/EntityTransaction”。

环境

面向开发人员的 IBM WAS 8.5.5.7 (Apache openjpa-2.2.3-SNAPSHOT-r422266)
Oracle Database 11g 企业版版本 11.2.0.1.0 - 64 位生产
Windows 7 64 位,配备 DELL Latitude core i7 2.8GHz 8G 内存和 SSD 硬盘

引用文献

<小时/>

固定代码

package sample.jpa.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;

import javax.persistence.PersistenceContext;
import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.SystemException;
import javax.transaction.UserTransaction;
import javax.transaction.SystemException;
import javax.naming.InitialContext;



import sample.jpa.AccountException;
import sample.jpa.Db2account;

@WebServlet("/CreateAccount")
public class CreateAccount extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
private static final long serialVersionUID = 1L;

@PersistenceContext(unitName="DB2AccountUnit")
EntityManager em;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}

synchronized protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
InitialContext context = null;
UserTransaction ut = null;

try {
context = new InitialContext();
ut = (UserTransaction)context.lookup("java:comp/UserTransaction");

if(ut == null){
System.out.println("UserTransactin is NULL");
}

// em.getTransaction().begin();
ut.begin();

long accno = Long.parseLong(request.getParameter("ACCNO"));
Db2account account1 = em.find(Db2account.class, accno);

if (account1 != null) {
throw new AccountException("Error : sample.jpa.servlet.CreateAccount : Account Number already exists:" + accno);
} else {
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
java.sql.Date dbDate = new java.sql.Date(format.parse(request.getParameter("DOP"), new ParsePosition(0)).getTime());

Db2account account = new Db2account();
account.setOwner(request.getParameter("OWNERNAME"));
account.setAccno(accno);
account.setAccountType(request.getParameter("ACCOUNTTYPE"));
account.setBalance(new BigDecimal(request.getParameter("BALANCE")));
account.setDateOpen(dbDate);

em.persist(account);
// em.getTransaction().commit();
ut.commit();

response.sendRedirect("Create_Account.jsp");
}
} catch (Exception e) {
e.printStackTrace();
// em.getTransaction().rollback();
try{
ut.rollback();
} catch (SystemException se){
se.printStackTrace();
}
}
}
}

最佳答案

做了更多研究并找到了原因。

EntityTransaction 旨在在没有可用 JTA 的情况下(例如独立 Java SE 环境)供资源本地使用。实体管理器由容器管理,并受容器的 JTA 事务管理器控制。

因此,我认为错误消息的含义应该是“您不能在 JEE 容器的 JTA 事务管理器管理的事务中使用由本地资源管理器管理的事务”。

修复

使用 RESOURCE_LOCAL transaction_type 创建另一个持久单元 DB2AccountUnitLocal。

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="DB2AccountUnit" transaction-type="JTA">
<jta-data-source>jdbc/DB2XA</jta-data-source>
<class>sample.jpa.Db2account</class>
<properties>
<property name="openjpa.Log" value="File=C:/opt/openjpa/org.apache.openjpa.log, DefaultLevel=INFO, Runtime=TRACE, Tool=INFO, SQL=TRACE, JDBC=TRACE" />
<property name="openjpa.ConnectionUserName" value="User" />
<property name="openjpa.ConnectionPassword" value="Password" />
</properties>
</persistence-unit>

<persistence-unit name="DB2AccountUnitLocal" transaction-type="RESOURCE_LOCAL">
<class>sample.jpa.Db2account</class>
<properties>
<property name="openjpa.ConnectionUserName" value="User" />
<property name="openjpa.ConnectionPassword" value="Password" />
<property name="openjpa.ConnectionURL" value="jdbc:oracle:thin:@localhost:1521:NR" />
<property name="openjpa.ConnectionDriverName" value="oracle.jdbc.driver.OracleDriver" />
</properties>
</persistence-unit>
</persistence>

更改了代码以使用应用程序管理实体管理器和其中的 EntityTransaction。

package sample.jpa.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sample.jpa.Db2account;
import sample.jpa.AccountException;

@WebServlet("/CreateAccount")
public class CreateAccount extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
tatic final long serialVersionUID = 1L;

//@PersistenceUnit(unitName="DB2AccountUnitLocal")
private EntityManagerFactory emf;
private EntityManager em = null;

public void init(ServletConfig config){
System.out.println("CreateAccount Servlet created..!");
emf = Persistence.createEntityManagerFactory("DB2AccountUnitLocal");
em = emf.createEntityManager();
}
public void destroy(){
System.out.println("CreateAccount Servlet destroyed..!");
em.close();
emf.close();
}
public CreateAccount() {
super();
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}

synchronized protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try{
long accno = Long.parseLong(request.getParameter("ACCNO"));
String ownerName = request.getParameter("OWNERNAME");
String strDate = request.getParameter("DOP");

long lgDate=new SimpleDateFormat("MM/dd/yyyy").parse(strDate,new ParsePosition(0)).getTime();
java.sql.Date dbDate=new java.sql.Date(lgDate);

String accType = request.getParameter("ACCOUNTTYPE");
BigDecimal balance = new BigDecimal(request.getParameter("BALANCE"));

em.getTransaction().begin();

Db2account account1 = em.find(Db2account.class, accno);

if(account1 != null){
throw new AccountException("Error : sample.jpa.servlet.CreateAccount : Account Number already exists:"+accno);
}
Db2account account = new Db2account();

account.setAccno(accno);
account.setAccountType(accType);
account.setBalance(balance);
account.setDateOpen(dbDate);
account.setOwner(ownerName);

em.persist(account);
em.getTransaction().commit();
}
catch (AccountException ae){
ae.printStackTrace();
em.getTransaction().rollback();
}
catch (Exception e){
e.printStackTrace();
em.getTransaction().rollback();
}
}
}

关于java - Web 中 OpenJPA 错误的原因 - 使用托管事务时无法访问 EntityTransaction,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32803179/

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