I'm using CMT in EJB3 state-less session beans. Also I've created my own Exception having the annotation "@ApplicationException (rollback=true)".
Do I have to use "context.setRollbackOnly()" when I want to rollback the transaction?
Can I just rollback the transaction by throwing an exception inside public method in the bean?
If so (the answer to Q#2 is yes) do I have to throw the exception out of the method by declaring the exception in the method or will it be sufficient to just throw an exception inside the method and handle it inside the same method itself? (I don't want to propagate the exception to the next level. I just want to rollback the exception.)
Thanks in advance. ;)
First of all, there is no rollback of an exception, it's a rollback of a transaction. If you throw your exception with @ApplicationException(rollback=true) , you don't have to rollback the transaction manually. Context. setRollbackOnly() forces the container to rollback the transaction, also if there is no exception.
Rolls back an explicit or implicit transaction to the beginning of the transaction, or to a savepoint inside the transaction. You can use ROLLBACK TRANSACTION to erase all data modifications made from the start of the transaction or to a savepoint. It also frees resources held by the transaction.
There are two ways to roll back a container-managed transaction. First, if a system exception is thrown, the container will automatically roll back the transaction. Second, by invoking the setRollbackOnly method of the EJBContext interface, the bean method instructs the container to roll back the transaction.
EJB Container/Servers are transaction servers and handles transactions context propagation and distributed transactions. Transactions can be managed by the container or by custom code handling in bean's code. Container Managed Transactions − In this type, the container manages the transaction states.
First of all, there is no rollback of an exception, it's a rollback of a transaction.
@ApplicationException(rollback=true)
, you don't have to rollback the transaction manually. Context.setRollbackOnly()
forces the container to rollback the transaction, also if there is no exception.@ApplicationException(rollback=true)
. If the exception is a RuntimeException
and the exception isn't caught, it forces the container to rollback the transaction. But watch out, the container will in this case discard the EJB instance.RuntimeException
, the transaction will be rolled back automatically. If you catch an checked exception inside the code, you have to use setRollbackOnly
to rollback the transaction.For further information, check out the free book Mastering EJB. It describes the rollback scenarios very well and is free for download.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With