Google

Jun 26, 2014

Transaction management with Spring and JTA interview questions and answers

Q. What is a Transaction? What does setAutoCommit do?
A.  A transaction is a set of operations that should be completed as a unit. If one operation fails then all the other operations fail as well. For example if you transfer funds between two accounts there will be two operations in the set

1. Withdraw money from one account.
2. Deposit money into other account.

These two operations should be completed as a single unit. Otherwise your money will get lost if the withdrawal is successful and the deposit fails. There are four characteristics (ACID properties) for a Transaction.

Atomicity
Consistency
Isolation
Durability
All the individual operations should either complete or fail. The design of the transaction should update the database correctly. Prevents data being corrupted by concurrent access by two different sources. It keeps transactions isolated or separated from each other until they are finished. Ensures that the database is definitely updated once the Transaction is completed.
Transactions maintain data integrity. A transaction has a beginning and an end like everything else in life. The setAutocommit(….), commit( ) and rollback( ) are used for marking the transactions (known as transaction demarcation). When a connection is created, it is in auto-commit mode. This means that each individual SQL statement is treated as a transaction and will be automatically committed immediately after it is executed. The way to allow two or more statements to be grouped into a transaction is to disable auto-commit mode:

try{
    Connection myConnection = dataSource.getConnection();
 
    // set autoCommit to false
    myConnection.setAutoCommit(false);

    withdrawMoneyFromFirstAccount(.............);   //operation 1
    depositMoneyIntoSecondAccount(.............);   //operation 2
 
    myConnection .commit();
}
catch(Exception sqle){
  try{
     myConnection .rollback();
  }catch( Exception e){}
}
finally{
   try{
        if( conn != null) {
             conn.close();
        }
  } catch( Exception e) {}
}


The above code ensures that both operation 1 and operation 2 succeed or fail as an atomic unit and consequently leaves the database in a consistent state. Also, turning auto-commit off will provide better performance.

Q. What is transaction demarcation? What are the different ways of defining transactional boundaries?
A. Data Access Objects (DAO) are transactional objects. Each operation associated with CRUD operations like Create, Update and/or Delete operations should be associated with transactions. Transaction demarcation is the manner in which transaction boundaries are defined. There are two approaches for transaction demarcation.

There are 2 types of transaction demarcation

1. Declarative transaction demarcation
2.  Programmatic transaction demarcation

1. Declarative transaction demarcation:

The programmer declaratively specifies the transaction boundaries using transaction attributes for an EJB via ejb-jar.xml deployment descriptor.

Note: Spring framework has support for declarative transaction demarcation by specifying transaction attributes via Spring config files. If you choose Spring framework to mark the transaction boundaries, then you need to turn off transaction demarcation in your EJB by marking it as NotSupported.

Q. How are these declarative transactions know when to rollback?

EJBs: When the EJB container manages the transaction, it is automatically rolled back when a System Exception occurs. This is possible because the container can intercept “System Exception”. However, when an "Application Exception" occurs, the container does not intercept it and therefore leaves it to the code to roll back using ctx.setRollbackOnly() method.

Spring Framework: Transaction declaration format is:

PROPAGATION_NAME,ISOLATION_NAME,readOnly,timeout_NNNN,+CheckedException1,-CheckedException2

By default transactions are rolled-back on java.lang.RuntimeException. You can control when transactions are committed and rolled back with the “+” or “-“ prefixes in the exception declaration. “+” means commit on exception (You can even force it on RuntimeException) and “-” means rollback on exception. You can specify multiple rules for rollback as “,” separated.

For example:  Following declaration will rollback transactions on RunTime exceptions and MyCheckedException, which is a checked exception.

PROPAGATION_REQUIRED,-MyCheckedException

2.  Programmatic transaction demarcation:

The programmer is responsible for coding transaction logic as shown above. The application controls the transaction via an API like JDBC API, JTA API, Hibernate API etc. JDBC transactions are controlled using the java.sql.Connection object. There are two modes: auto-commit and manual commit. Following methods are provided in the JDBC API via non-XA java.sql.Connection class for programmatically controlling transactions:

public void setAutoCommit(boolean mode);
public boolean getAutoCommit();
public void commit();
public void rollback();


For XA-Connections use the following methods on javax.transaction.UserTransaction.

public void begin();
public void commit();
public void rollback();
public int getStatus();
public void setRollbackOnly();
public void setTransactionTimeOut(int)




Q. What support does Spring framework have for transaction management?
A.

1. Spring supports both global transactions across multiple transactional resources through JTA and resouce specific local transaction associated with a JDBC connection. It provides a consistent programming model to support both local and global transactions. You write your code once, and it can benefit from different transaction management strategies in different environmen.

2. Supports both declarative transaction management via AOP and programmatic transaction management with the Spring Framework transaction abstraction which can run over any underlying transaction infrastructure. With the preferred declarative model, developers typically write little or no code related to transaction management.

Step 1: Define your transaction manager in a Spring context file

<bean id="txnManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"/>
..
<tx:annotation-driven transaction-manager="txnManager"/>


Step 2: In your business service layer that makes calls to a number of daos, annotate to define your transaction demarcation

@Transactional
public int addUser(User user) {
    ...
}


The @Transactional annotation takes propagation and isolation levels as attributes, and the defaults being Propagation : Required and Isolation level : Default.

3. Spring framework has support for most transactional APIs such as JDBC, Hibernate, JPA, JDO, JTA etc. All you need to do is use proper transaction manager implementation class. For example org.springframework.jdbc.datasource.DriverManagerDataSource for JDBC transaction management and org.springframework.orm.hibernate3.HibernateTransactionManager for Hibernate as ORM tool.

4. The support for programmatic transaction management is provided via TransactionTemplate or PlatformTransactionManager implementation.

private PlatformTransactionManager txnManager;

public int addUser(User user) {
  TransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
  TransactionStatus status = transactionManager.getTransaction(transactionDefinition);
  
   try{
      //....transactional operations
   
   transactionManager.commit(status);
   }
   catch(Exception ex){
      transactionManager.rollback(status);
   }
  
}


The Transaction Definition object encapsulates the transactional properties such as the isolation level, propagation behavior, timeout etc. The Transaction Status object represents the status of the executing transaction whether it is in new, completed, etc.

Q. What is a distributed (aka JTA/XA) transaction? How does it differ from a local transaction?
A. There are two types of transactions:

Local transaction: Transaction is within the same database. As we have seen above, with JDBC transaction demarcation, you can combine multiple SQL statements into a single transaction, but the transactional scope is limited to a single database connection. A JDBC transaction cannot span multiple databases.

Distributed Transaction (aka Global Transaction, JTA/XA transaction): The transactions that constitute a distributed transaction might be in the same database, but more typically are in different databases and often in different locations. For example, A distributed transaction might consist of money being transferred from an account in one bank to an account in another bank. You would not want either transaction committed without assurance that both will complete successfully. The Java Transaction API (JTA) and its sibling Java Transaction Service (JTS), provide distributed transaction services for the JEE platform. A distributed transaction (aka JTA/XA transaction) involves a transaction manager and one or more resource managers. A resource manager represents any kind of data store. The transaction manager is responsible for coordinating communication between your application and all the resource managers. A transaction manager decides whether to commit or rollback at the end of the transaction in a distributed system. A resource manager is responsible for controlling of accessing the common resources in the distributed system.

Q. What is two-phase commit?
A.  two-phase commit is an approach for committing a distributed transaction in 2 phases.

Q. What do you understand by JTA and JTS?
A. JTA is a high level transaction interface which allows transaction demarcation in a manner that is independent of the transaction manager implementation. JTS specifies the implementation of a Transaction Manager which supports the JTA. The code developed by developers does not call the JTS methods directly, but only invokes the JTA methods. The JTA internally invokes the JTS routines.

Q. What is a XA resource?
A. The XA specification defines how an application program uses a transaction manager to coordinate distributed transactions across multiple resource managers. Any resource manager that adheres to XA specification can participate in a transaction coordinated by an XA-compliant transaction manager.


JTA transaction demarcation requires a JDBC driver that implements XA interfaces like javax.sql.XADatasource, javax.sql.XAConnection and javax.sql.XAResource. A driver that implements these interfaces will be able to participate in JTA transactions. You will also require to set up the XADatasource using your application server specific configuration files, but once you get a handle on the DataSource via JNDI lookup, you can get a XA connection via javax.sql.DataSource.getConnection() in a similar manner you get a non-XA connections. XA connections are different from non-XA connections and do not support JDBC’s auto-commit feature. You cannot also use the commit( ), rollback( ) methods on the java.sql.Connection class for the XA connections. A J2EE component can begin a transaction programmatically using javax.transaction.UserTransaction interface or it can also be started declaratively by the EJB container if an EJB bean uses container managed transaction. For explicit (i.e. programmatic) JTA/XA transaction you should use the UserTransaction.begin( ), UserTransaction.commit() and UserTransaction.rollback() methods. For example:

// programmatic JTA transaction
InitialContext ctx = new InitialContext();
UserTransaction utx = (UserTransaction)ctx.lookup(“java:comp/UserTransaction”);

try { 
    //…
    utx.begin();
    //….
    DataSource ds = getXADatasource();
    Connection con = ds.getConnection(); // get a XAconnection.
    PreparedStatement pstmt = con.prepareStatement(“UPDATE Employee emp where emp.id =?”);
    pstmt.setInt(1, 12456);
    pstmt.executeUpdate(); 
    
   utx.commit();//transaction manager uses two-phase commit protocol to end transaction  
}
catch(SQLException sqle){
    utx.rollback();
    throw new RuntimeException(sqle);
}


Q. Why JTA transactions are more powerful than JDBC transactions?
A. JTA transactions are more powerful than JDBC transactions because a JDBC transaction is limited to a single database whereas a JTA transaction can have multiple participants like:
  • JDBC connections.
  • JMS queues/topics.
  • Enterprise JavaBeans (EJBs).
  • Resource adapters that comply with JEE Connector Architecture  (JCA) specification.  

Labels: , , ,

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home