Rule Definition
One of the primary advantages of an Application Server is the support of declarative transactions. Without this feature, transactions must be controlled using explicit transaction demarcation. Explicit demarcation is difficult for developers to use at best, particularly if you are new to transactional systems. In addition, explicit transaction demarcation requires that the transactional code be written within the business logic, which reduces the clarity of the code and more importantly creates inflexible distributed objects. Once transaction demarcation is "hardcoded" into the business object, changes in transaction behaviour require changes to the business logic itself.
Declarative transactions make it easier for you to create robust transactional applications. The risk to not use them is data corruption.
Remediation
Using transaction attributes simplifies the construction of transactional applications by reducing the risks associated with improper use of transactional protocols like JTA. It is more efficient and easier to use transaction attributes than to control transactions explicitly. This can be done through EJB or Spring.
Violation Code Sample
programmatic transaction demarcation: sample 1: @Stateless @TransactionManagement(TransactionManagementType.BEAN) public class UserServiceImpl { UserDAO userDAO; public void update(User user) throws Exception { InitialContext context = new InitialContext(); //reference of javax.transaction.UserTransaction UserTransaction transaction = (UserTransaction)context.lookup("UserTransaction"); try { //explicit transaction demarcation transaction.begin();// starting the transaction : violation ....... transaction.commit(); // committing: violation } catch (Exception up) { transaction.rollback(); throw up; } } }
Fixed Code Sample
use container-managed transaction demarcation (@Transactional Annotation or Configure Transactions with XML) @Stateless public class UserServiceImpl { UserDAO UserDAO; @Resource SessionContext context; @TransactionAttribute(TransactionAttributeType.REQUIRED) public void update(User user) throws Exception { try { userDAO.update(user); } catch (Exception up) { context.setRollbackOnly(); throw up; } } }
Reference
http://docstore.mik.ua/orelly/java-ent/ebeans/ch08_02.htm
Related Technologies
JEE
Technical Criterion
Programming Practices - Unexpected Behavior
About CAST Appmarq
CAST Appmarq is by far the biggest repository of data about real IT systems. It's built on thousands of analyzed applications, made of 35 different technologies, by over 300 business organizations across major verticals. It provides IT Leaders with factual key analytics to let them know if their applications are on track.