This post is triggered by one of Treimin's questions. I was trying to test a simple case of ApplicationException, I cannot get it to work. I am expecting to see the value of x as 1 because in the method I set it to 5 and after that I throw the ApplicationException, CreditValidationException which has the rollback attribute to true. The value of x being returned is 5. What am I missing.
What you are missing is the fact that when a transaction rolls back, it rolls back all resource managers enlisted in the transaction. A resource manager is a database, JMS, JPA entity manager and so on. Your bean is not one, and it will not reset the value of the x variable. You would have to implement your own resource manager with XAResource interface, but it is not trivial. What you want to do is easiest done with SessionSynchronisation.afterCompletion().
Thanks for the response. To verify that the transaction was rolledback, I added SessionSynchronization interface to my bean and checked the committed flag in afterComplete method was false. So I am good so far.
I had this misunderstanding that the whole result of the bean method would be rolledback when the transaction is rolledback. Your explanation makes sense. But I was wondering that there would be cases where you would want the result of the whole thing to be rolledback, some pseudo code follows
modifyX{
x=5;
persistx(); // this fails, the db is not updated and the transaction is rolledback
}
Now you have a scenario where the bean value is out of sync with the DB. Right now every application has to handle this in their own way, somehow syncing up the values. Would it make sense for the container to provide this behavior or is there a bigger issues/limitations here I am not thinking of. (I do understand that this may not be the required behavior in all cases).
PS - Slightly off topic, How did your test go, I knew you were going to take last week or so. Would you like to share your experience and your preparation.
When you implement the SessionSynchronization, aftercompletion is one of the 3 methods you have to implement. It is a handy method to see if the transaction committed or rolled back. Hope that helps.
If you have this requirement, to roll back the values, you need a way to remember it then, it is up to you. For example, you can create additional fields to remember the state, it is thread safe as only one thread at a time will access the bean anyways.