gpt4 book ai didi

java - JPA事务提交奇怪的行为

转载 作者:行者123 更新时间:2023-12-02 06:04:34 25 4
gpt4 key购买 nike

我正在尝试了解 jpa 事务工作。

假设我有以下 persistence.xml:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.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_2_0.xsd">
<persistence-unit name="survex" transaction-type="JTA">
<jta-data-source>jdbc/MyDatabase</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
</properties>
</persistence-unit>
</persistence>

以及以下使用嗅探 mysql 服务器的测试代码:

public class Servlet extends HttpServlet {

@PersistenceContext(type = PersistenceContextType.TRANSACTION)
EntityManager em;

@Resource
UserTransaction utx;

Log log;

public void initialize() {
log = em.find(Log.class, 1);
}

public void meth1() throws SystemException, NotSupportedException, HeuristicRollbackException, HeuristicMixedException, RollbackException {
utx.begin();
em.merge(log);
log.setMessage(String.valueOf(Math.random()));
utx.commit();
}

public void meth2() throws SystemException, NotSupportedException, HeuristicRollbackException, HeuristicMixedException, RollbackException {
utx.begin();
em.merge(log);
log.setMessage(String.valueOf(Math.random()));
utx.commit();
}

protected void doGet(HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {

try {

this.initialize();
this.meth1(); // NOTHING HAPPENS!
this.meth2();
// SET autocommit=0;
// UPDATE LOG SET message = '0.1523804781755964' WHERE (id = 1);
// commit;
// SET autocommit=1;

} catch ... {
...
}
response.getWriter().write("test");
}
}

为什么?!为什么 method1 调用没有提交?

最佳答案

该错误是一个典型错误:调用 merge() 后传递的日志未得到管理。仅管理返回的实例。请尝试以下操作:

public void meth1() throws SystemException, NotSupportedException, HeuristicRollbackException, HeuristicMixedException, RollbackException {
utx.begin();
Log newLog = em.merge(log);
newLog.setMessage(String.valueOf(Math.random()));//we make the changes to the managed instance
utx.commit();
}

关于java - JPA事务提交奇怪的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22406303/

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