Saturday, April 16, 2016

javax.transaction.Transactional

Suppose we have a managed CDI bean exposing to JSF-EL two methods:

public void methodA(){
    //do some additional stuff
    methodB();
}
@Transactional
public void methodB(){
    //do actual work by several EJB calls
}

At a first glance you could think:

  • If we call methodA(from a JSF view) we would get a transaction started and all work will be done inside this transaction
  • If we call methodA we will get the same result for whatever methodA is doing

Well, while the first assumption works as stated the second is, surprise, wrong. Each individual call to the mentioned EJB will trigger it's own transaction.

This behaviour is due to the following not obvious at first glance fact: JSF will call CDI methods through a proxy that wraps the actual instance and fires interceptors; in our second case interceptors have been already fired before methodA was actually called and no other interceptors (that would trigger transaction management) will be called due to the fact that instance not proxy methodB will be called.

U3VwcG9zZSB3ZSBoYXZlIGEgbWFuYWdlZCBDREkgYmVhbiBleHBvc2luZyB0byBKU0YtRUwgdHdvIG1ldGhvZHM6DQoNCmBgYGphdmENCnB1YmxpYyB2b2lkIG1ldGhvZEEoKXsNCgkvL2RvIHNvbWUgYWRkaXRpb25hbCBzdHVmZg0KCW1ldGhvZEIoKTsNCn0NCkBUcmFuc2FjdGlvbmFsDQpwdWJsaWMgdm9pZCBtZXRob2RCKCl7DQoJLy9kbyBhY3R1YWwgd29yayBieSBzZXZlcmFsIEVKQiBjYWxscw0KfQ0KYGBgDQpBdCBhIGZpcnN0IGdsYW5jZSB5b3UgY291bGQgdGhpbms6DQoqIElmIHdlIGNhbGwgYG1ldGhvZEFgKGZyb20gYSBKU0YgdmlldykgIHdlIHdvdWxkIGdldCBhIHRyYW5zYWN0aW9uIHN0YXJ0ZWQgYW5kIGFsbCB3b3JrIHdpbGwgYmUgZG9uZSBpbnNpZGUgdGhpcyB0cmFuc2FjdGlvbg0KKiBJZiB3ZSBjYWxsIGBtZXRob2RBYCB3ZSB3aWxsIGdldCB0aGUgc2FtZSByZXN1bHQgZm9yIHdoYXRldmVyIGBtZXRob2RBYCBpcyBkb2luZw0KDQpXZWxsLCB3aGlsZSB0aGUgZmlyc3QgYXNzdW1wdGlvbiB3b3Jr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