Java Reference
In-Depth Information
6.2.7. Using CMT effectively
CMTs are straightforward and much easier to use as compared to BMTs. If you don't an-
notate your beans or provide a deployment descriptor, your beans will execute with CMTs
and a transaction attribute of REQUIRED . This is a “safe” setting. Your application should
work without any additional effort provided application exceptions aren't thrown. There
are a couple of things that you can do to more effectively use CMTs and ensure that your
application is logically correct and easy to maintain.
For maintainability, you generally want to identify the logical transactions that are taking
place and assign a method as being responsible for the transaction. This method is respons-
ible for two things: catching application exceptions and setting the rollback flag. Hand-
ling of application exceptions should be uniform and not distributed throughout a set of
beans that are participating in a transaction. If an application exception fails to roll back
or doesn't cause a rollback, it's often hard to pinpoint the problem spot if exception hand-
ling is distributed and handled nonuniformly. Regarding rollbacks, rollback logic should
be centralized, preferably in the method that serves as a gateway for the transaction. As in
the application exceptions, the more distributed the handling of rollbacks, the harder the
code becomes to verify, test, and maintain. Also, prior to performing long-running tasks,
make sure to check getRollbackOnly() to find out if it's worth proceeding. There's
no sense in performing a long-running operation if it's just going to be reverted.
When setting the transaction attributes on methods in a class as well as at the class level,
set the most restrictive level required by a method of the class. This minimizes the chance
that a method that requires a more stringent transaction attribute isn't accidently executed
with a lesser one. For example, it would be bad if you set the class level as SUPPORTS and
then added a new method that required a REQUIRED but forgot to annotate it. This method
would then essentially execute in auto-commit mode. It's better to use a transaction when
you don't need to than fail to use a transaction when it's critical.
Correctly handling application exceptions is critical, because the container doesn't auto-
matically roll back when an application exception is thrown. If you catch an application
exception that requires a rollback, make sure it's handled in the catch . Where possible,
attempt to annotate application exceptions with @ApplicationException . This can
greatly reduce the number of places where a forgotten setRollbackOnly() could trip
your application.
Search WWH ::




Custom Search