JPA:多笔交易

发布于 2024-12-28 18:57:03 字数 802 浏览 0 评论 0原文

我正在尝试使用同一事务实体进行 2 个不同的数据库调用。我知道我可以在 begin()commit() 之间进行询问,但我尝试这样做只是为了教育目的。

EntityTransaction transaction = em.getTransaction();
EventService eventService = new EventService();
transaction.begin();
Event currentEvent = eventService.read(eventId);
transaction.commit();

if (currentEvent != null){
    CommentService commentService = new CommentService();
    transaction.begin();
    commentList = commentService.getList(1, id, 50);
    transaction.commit();
}

这段代码抛出:

异常描述:交易当前处于活动状态

这是正常的,因为我正在尝试对已打开的事务执行 begin()

每当我必须使用数据库时,排除第二个 transaction.begin() 并仅使用 commit() 是否正确?

LE: 我正在使用 EclipseLink 和 RESOURCE_LOCAL

I'm trying to make 2 different DB calls with the same transaction entity. I know that I can make both interrogations between begin() and commit() but I'm trying this for educational purposes only.

EntityTransaction transaction = em.getTransaction();
EventService eventService = new EventService();
transaction.begin();
Event currentEvent = eventService.read(eventId);
transaction.commit();

if (currentEvent != null){
    CommentService commentService = new CommentService();
    transaction.begin();
    commentList = commentService.getList(1, id, 50);
    transaction.commit();
}

This piece of code throws :

Exception Description: Transaction is currently active

which is normal knowing that I'm attempting a begin() to an already opened transaction.

Is it correct to exclude the second transaction.begin() and just use commit() whenever I have to work with the DB?

LE:
I'm using EclipseLink and RESOURCE_LOCAL

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

温柔嚣张 2025-01-04 18:57:03

发生这种情况是因为 transacton-type 设置为 RESOURCE_LOCAL
在这种情况下,您必须创建一些应处理 EntityManagerEntityTransactionSingleTon 类。

This happens because the transacton-type is set to RESOURCE_LOCAL.
In this cases you must create some SingleTon classes which should handle the EntityManager and the EntityTransaction.

哭泣的笑容 2025-01-04 18:57:03

奇怪的。这应该有效。您使用哪个 JPA 提供商?也许启用日志记录以查看发生了什么。

Odd. This should work. What JPA provider are you using? Perhaps enable logging to see what is going on.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文