save up to 40%

EJB Transaction

Are you preparing for IT certification? With practice questions, study notes, interactive quizzes, tips and technical articles, uCertify PrepKits ensure that you get a solid grasp of core technical concepts to ace your certification exam in first attempt.

EJB Transaction

Rating:

A transaction is a unit of work that consists of a group of activities performed as a unit such that either all or none of them succeed. An example of where transactions could take place is an online bookstore. In an online bookstore, the purchasing of books involves the following steps:

  1. A customer creates an account with the bookstore.
  2. He chooses the books from a given list and adds them to the shopping cart.
  3. He is asked for his credit card information.

  4. The credit card information is verified, and the books are delivered to the customer.

Now imagine what will happen if any of these steps fail. If the customer does not get the books of his choice or the credit card information cannot be verified, the whole transaction will fail. In other words, everything will return to the stage before the transaction failed.

Every transaction has a beginning and an end. The process of marking the transaction boundaries is known as transaction demarcation. Transactions either commit or roll back to their initial stage. In EJB, a transaction must pass the ACID test, i.e., it must meet the following requirements:
  • Atomicity: A transaction is an atomic unit of work. This means that in order to be in a transaction, a group of activities should succeed, or all of them should fail. If a transaction is interrupted, all previous steps within that transaction are undone. For example, while withdrawing money from an ATM, the account balance of the cardholder is checked, the money is withdrawn, and the balance is deducted. If any of these steps fail, the transaction should be rolled back as if nothing happened.

  • Consistency: This property of transaction refers to the behavior of data after a transaction is completed. Whether a transaction commits or rolls back, it must leave the data in a consistent state. When money is withdrawn from an ATM, the amount of money deducted from the balance must be equal to the money that the card holder receives.

  • Isolation: A transaction must be performed such that it is unaffected by any other part of the system. This means the data that a transaction accesses cannot be affected by any other part of the system until the transaction is completed. This property is directly related to the consistency property, as the violation of this property may leave data in an inconsistent state.

  • Durability: This property of transaction deals with data persistence. If a transaction deals with changing some data stored in a database, the results of a transaction must be reflected in the database. This ensures that the changes are not lost if the system crashes.
In EJB, transactions can be managed by the container or the bean developer. Transactions managed by the container are known as container-managed transactions or CMT or declarative transactions, and those managed by the developer are known as bean-managed transactions or BMT or programmatic transactions. In a bean-managed transaction, the developer is required to write code for handling the transaction programmatically. In a container-managed transaction, the developer is required to enter information related to the transaction in the deployment descriptor file.

Transaction management in EJB involves two interfaces, namely UserTransaction and EJBContext.

The UserTransaction interface offers methods that are needed to manage transaction boundaries. The methods in this interface are only for the programmatic transaction. The methods present in the UserTransaction interface are as follows:
  • begin(): It creates a new transaction.

  • commit(): This method commits a transaction, i.e., it successfully completes a transaction.

  • getStatus(): This method is used to obtain the current status of a transaction. The status in a transaction can be in progress or marked for rollback.

  • rollback(): This method is used to roll back the current transaction. A transaction is rolled back when there is a system exception in the transaction.

  • setRollbackOnly(): As the name suggests, this method modifies a transaction such that it must roll back to its initial state.

  • setTransactionTimeout(): This method modifies the default transaction timeout set by the server.
The EJBContext interface provides the runtime environment for the enterprise beans instances. It is the super interface for the SessionContext, EntityContext, and MessageDrivenContext interfaces. The methods present in the EJBContext interface can be divided into three categories:

  1. Methods that can be called only by the BMT beans
    • getUserTransaction(): This method is used to get a reference to a UserTransaction object.
  2. Methods that can be called only by the CMT beans
    • getRollbackOnly(): This method returns the status of the current thread for a CMT. It returns true if the current transaction is marked for a rollback.

    • setRollbackOnly(): This method modifies a transaction such that it must roll back to its initial state.
  3. Methods that can be called by both the BMT beans and the CMT beans
    • getCallerPrincipal(): This method is related to Java security, which identifies the user using java.security.Principal.

    • getEJBHome(): This method is used by the bean to obtain the remote home interface. It throws an IllegalStateException if the caller bean has no remote home.

    • getEJBLocalHome(): This method is used by the bean to obtain the local home interface. It throws an IllegalStateException if the caller bean has no local home.

    • isCallerInRole(): As an argument, it takes one of the roles defined in the deployment descriptor. It returns true if the caller has the security role specified in the parameter.
Container-managed transaction

In the container-managed transaction, the transaction boundaries are taken care by the container. To use the container-managed transaction, the transaction type must be specified in the deployment descriptor as follows:

<transaction-type>Container</transaction-type>

The advantages of the container-managed transaction are as follows:
  • The container manages the transaction behavior of the bean. This frees the application provider from writing transaction demarcation code in the component.

  • It is less error-prone because the container handles transaction demarcation automatically.

  • It is easier to compose multiple enterprise beans to perform a certain task with specific transaction behavior. Also, it is easier to maintain, as transaction behavior can be changed without making any change in the code.
Bean-managed transaction

Bean-managed transactions are written and handled programmatically by writing the code for the transaction. To use the bean-managed transaction demarcation, the transaction type must be specified in the deployment descriptor as follows:

<transaction-type>Bean</transaction-type>

A developer needs to use the javax.transaction.UserTransaction interface to explicitly demarcate transaction boundaries. Entity beans always use container-managed transaction demarcation. Session beans can use either container-managed or bean-managed transaction demarcation, but not at the same time.

Marking transaction in the deployment descriptor

BMT beans require the deployment descriptor only for marking the transaction type. The type of transaction in the deployment descriptor is marked as follows:

<enterprise-beans>
<session>
      ........
         <transaction-type>Bean</transaction-type>
      ........
</enterprise-beans>

CMT beans require the deployment descriptor for two reasons as follows:

  1. Marking the transaction type
    <enterprise-beans>
    <session>
          ........
             <transaction-type>Container</transaction-type>
          ........
    </enterprise-beans>

  2. Marking method name and attribute type
    <assembly-descriptor>
       <container-transaction>
          <method>
             <ejb-name>FirstBean</ejb-name>
             <method-name>method1</method-name>
          </method>
       <trans-attribute>Required</trans-attribute>
    <assembly-descriptor>


Transaction attributes

Transaction attributes are used in a container-managed transaction to determine the behavior of the transaction. The attribute is specified using the <trans-attribute> of the deployment descriptor file. The attributes in EJB are of the following six types:
  • Required: Required is used as a default transaction attribute to ensure that methods are invoked within a Java transaction API (JTA) transaction context. It causes the enterprise bean to use existing transactional context if it exists, or to create one otherwise.

  • RequiresNew: A method with RequiresNew as the transaction attribute will always run with a new transaction. If the method is called within the current transaction context, the current transaction will be suspended until the method call returns. This attribute should be used when the results of the method must be committed regardless of whether the caller's transaction succeeds or fails.

  • Mandatory: Mandatory always requires an existing transaction. The container throws an exception if the method with mandatory as the attribute is called without an existing transaction context.

  • Supports: Supports causes a method to run within the current transaction context. If a transaction does not exist, the method runs within an unspecified transaction context.

  • NotSupported: If the method is called within the current transaction context, the current transaction will be suspended until the method call returns. It always causes a method to run within an unspecified transaction context.

  • Never: It always requires a new transaction. The container throws an exception if the method with never as the attribute is called within an existing transaction context. This attribute is used to ensure that a transactional client does not access methods that are not capable of participating in the transaction.
For a session bean, the transaction attributes must be specified for the methods defined in the bean's remote interface and all its superinterfaces, excluding the methods of the javax.ejb.EJBObject interface. A session bean can use the following transaction attributes:
  • Mandatory
  • RequiresNew
  • Required
  • Supports
  • NotSupported
  • Never
For an entity bean, the transaction attributes must be specified as follows:
  • In the methods defined in the bean's remote interface and all its superinterfaces, excluding the getEJBHome(), getHandle(), getPrimaryKey(), and isIdentical() methods.

  • In the methods defined in the bean's home interface and all its superinterfaces, excluding the getEJBMetaData() and getHomeHandle() methods.
An entity bean can use the following transaction attributes:
  • Mandatory
  • RequiresNew
  • Required
A message-driven bean does not have a client view. The transaction attribute for a message-driven bean must be specified for the bean's onMessage() method. A message-driven bean can use the following transaction attributes:
  • Required
  • NotSupported


Rating:



Other articles

Click here to Article home

 
uCertify.com | Our Company | Articles | Privacy | Security | Contact Us | News and Press Release | uCertify India
MCSE: MCSA, MCTS, MCITP    JAVA Certification: SCJP, SCWCD Cisco Certification: CCNA, CCENT, A+, Network+, Security+
Oracle Certification: OCP 9i, OCP 10g, OCA 9i, OCA 10g CIW foundation    EC-212-32    CISSP    Photoshop ACE    Adobe Flash ACE
© 2008 uCertify.com. All rights reserved. All trademarks are the property of their respective owners.