CDI @TransactionAttribute for bean

若如初见. 提交于 2019-12-10 10:12:28

问题


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);
    }
}

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));
    }
}

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.

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.

Could anyone clear my confusion? Do really CDI define @TransactionAttribute for plain beans?

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?

Best regards, Petar


回答1:


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



来源:https://stackoverflow.com/questions/6908191/cdi-transactionattribute-for-bean

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!