Bean的CDI @TransactionAttribute [英] CDI @TransactionAttribute for bean
问题描述
我正在测试应用程序上的 CDI
。我有一个 DAO
,它注入了一个容器管理的 JTA
持久性上下文,如下所示:
I am experimenting with CDI
on a test application. I have a DAO
which injects a container managed JTA
persistence context like this:
public class TestDAO implements Serializable {
@PersistenceContext
private EntityManager entityManager;
public void insertEntity(Test test) {
entityManager.persist(test);
}
}
现在我有一个像这样的CDI控制器bean:
Now I have a CDI controller bean like this:
@Named
@SessionScoped
public class TestController implements Serializable {
@Inject
private TestDAO testDAO;
public void finishGame() {
testDAO.insertEntity(new Test(1, 2, 3));
}
}
如果运行此命令,则会收到错误消息尝试插入实体时 DAO
,因为没有可用的活动事务。到现在为止还挺好。我可以通过使控制器bean成为有状态的 EJB
来解决此问题,该EJB将在交易中包装 finishGame()
。
If I run this, I receive an error in the DAO
when trying to insert the entity, because there is no active transaction available. So far so good. I can solve this by making the controller bean a stateful EJB
which will wrap the finishGame()
in a transaction.
但是,假设我不想要 EJB
。作为测试,我用 @TransactionAttribute
注释了 finishGame()
并奏效了(控制器bean不是 EJB
)。所以我的问题是:它是如何工作的? CDI
是否为普通豆定义 @TransactionAttribute
?我知道 Seam Persistence Module
可以做到这一点,但是我没有使用它。实际上,我将其添加到项目中,但是之后又删除了它,因为我收到了尴尬的异常。
But let assume I don't want an EJB
. As a test I annotated the finishGame()
with the @TransactionAttribute
annotation and it worked(the controller bean is NOT an EJB
). So my question is: how does it work? Does the CDI
define @TransactionAttribute
for plain beans? I know that Seam Persistence Module
does this, but I am not using it. Actually I added it to the project, but I removed it after, because I received awkward exceptions.
有人可以消除我的困惑吗?真的 CDI
为普通豆定义了 @TransactionAttribute
吗?
Could anyone clear my confusion? Do really CDI
define @TransactionAttribute
for plain beans?
P.S。我还有另一个问题。我看到的趋势是将所有 EJB
注释移植到普通bean。那么 EJB
将来会过时吗?我的意思是我在 JIRA
中看到将来会为普通豆添加 @TransactionAttribute
(任务仍然没有解决)。那么,这是否使EJB黯然失色,实现了重复功能?
P.S. I have another sort of question. I see the tendencies is to port all EJB
annotations to plain beans. So will EJBs
become obsolete in the future? I mean I saw in JIRA
that @TransactionAttribute
will be added in the future for plain beans(the task is still not resolved). So isn't this eclipsing EJBs, sort of duplicating functionality?
最诚挚的问候,
Petar
Best regards, Petar
推荐答案
您需要定义一个事务拦截器。基本上定义一个@Transactional批注,并拦截所有使用其注释的方法。在拦截器中,才开始,提交或回滚事务。当事务传播进入画面时,它将变得更加复杂。因此,请检查Seam是否没有任何可立即使用的 http://seamframework.org/Seam3/PersistenceModule
You need do define a transaction interceptor. Basically define a @Transactional annotation and intercept all methods annotated with it. In the interceptor just begin, commit or rollback the transaction. It gets more complicated when transaction propagation comes into the picture. So check if Seam doesn't have anything ready-to-use http://seamframework.org/Seam3/PersistenceModule
这篇关于Bean的CDI @TransactionAttribute的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!