Java EE 6 CDI 事件是事务性的吗?

发布于 2024-10-03 06:01:22 字数 143 浏览 0 评论 0原文

Java EE 6 CDI 事件是事务性的吗?

如果我在事务中触发事件,然后回滚该事务,事件侦听器的效果是否也会回滚?

此行为是否依赖于事件侦听器本身支持事务?

如果我尝试从事件侦听器内回滚异常,它会回滚触发该事件的事务吗?

Are Java EE 6 CDI events transactional?

If I fire an event in a transaction, and subsequently roll back the transaction, are the effects of the Event listener rolled back as well?

Is this behaviour dependent on the event listener itself supporting transactions?

What about if I try and roll-back the exception from within then event listener, does it roll-back the transaction that fired the event?

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

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

发布评论

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

评论(1

三生一梦 2024-10-10 06:01:22

从 CDI 1.0 规范的事件章节中,可以定义通过指定正在观察的 TransactionPhase 来将事件设为“事务性”,其中 TransactionPhase 是以下之一:

  • IN_PROGRESS、
  • BEFORE_COMPLETION、
  • AFTER_COMPLETION、
  • AFTER_FAILURE、
  • AFTER_SUCCESS

这样的声明如下所示:

void onDocumentUpdate(@Observes(during=AFTER_SUCCESS) @Updated Document doc) { ... }

如果观察者未声明为“事务性”,则容器立即调用观察者,否则它会使用 JTA 同步注册观察者方法,以便稍后在事务完成阶段调用。

然而:

任何在事务完成之前调用的观察者方法都可以调用 setRollbackOnly() 来强制事务回滚。观察者方法不能直接发起、提交或回滚 JTA 事务。

如果观察者方法抛出异常(并且本身不是“事务性的”),则异常将中止事件的处理。

因此,为了实现我正在寻找的行为,我相信我会将我的观察者注册为“事务性”,并指定 BEFORE_COMPLETION TransactionPhase。如果我想回滚启动该事件的事务,我会调用 setRollbackOnly()。

From the events chapter of the CDI 1.0 specification, one can define an event to be "transactional" by specifying the TransactionPhase one is observing, where TransactionPhase is one of:

  • IN_PROGRESS,
  • BEFORE_COMPLETION,
  • AFTER_COMPLETION,
  • AFTER_FAILURE,
  • AFTER_SUCCESS

Such a declaration looks like:

void onDocumentUpdate(@Observes(during=AFTER_SUCCESS) @Updated Document doc) { ... }

If the observer is not declared to be "transactional", then the container calls the observer immediately, otherwise it registers the observer method for later invocation during the transaction completion phase, using a JTA Synchronization.

However:

Any observer method called before completion of a transaction may call setRollbackOnly() to force a transaction rollback. An observer method may not directly initiate, commit or rollback JTA transactions.

If the observer method throws an exception (and is itself not "transactional") the exception aborts processing of the event.

So, to achieve the behaviour I'm looking for, I believe I would register my observer as "transactional", and specify the BEFORE_COMPLETION TransactionPhase. I would then call setRollbackOnly() if I wanted to rollback the transaction that initiated the event.

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