开发者

CDI @TransactionAttribute for bean

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 i开发者_运维问答nsert 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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜