Saturday, February 7, 2009

Connection Pooling and Transaction implementation using apache commons and JTA

The following is code for creating connection pool using apache commons-dbcp and transaction using java transaction api.
Download commons-dbcp-all-1.3.jar



import java.sql.Connection;
import java.sql.PreparedStatement;


import javax.sql.DataSource;
import javax.sql.XAConnection;
import javax.sql.XADataSource;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
import org.apache.commons.dbcp.managed.BasicManagedDataSource;



public class Main {

public void saveData() throws Exception{
DataSource dataSource = (DataSource)getDataSource();
XADataSource xaDS=(XADataSource) dataSource ;
XAConnection xaCon = (XAConnection) dataSource.getConnection();
XAResource xaRes = xaCon.getXAResource();
Connection connection = xaCon.getConnection();
Xid xid = new MyXid(100, new byte[]{0x01}, new byte[]{0x02});
String sql ="";//insertion query
int ret;
xaRes.start(xid, XAResource.TMNOFLAGS);
connection.setAutoCommit(false);
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.executeUpdate();
connection.commit();
connection.setAutoCommit(true);
xaRes.end(xid, XAResource.TMSUCCESS);
ret = xaRes.prepare(xid);
if (ret == XAResource.XA_OK) {
xaRes.commit(xid, false);
}
else {
xaRes.rollback(xid);
connection.rollback();
}
}
public BasicManagedDataSource getDataSource(){
BasicManagedDataSource basicManagedDataSource = new BasicManagedDataSource();
basicManagedDataSource.setDriverClassName("com.mysql.jdbc.Driver");
basicManagedDataSource.setDefaultAutoCommit(false);
basicManagedDataSource.setMaxActive(20);
basicManagedDataSource.setUrl("jdbc:mysql://localhost:3306/pralink");
basicManagedDataSource.setUsername("root");
basicManagedDataSource.setPassword("mysql");
basicManagedDataSource.setMaxIdle(10);
basicManagedDataSource.setXADataSource("com.mysql.jdbc.jdbc2.optional.MysqlXADataSource");//oracle.jdbc.xa.client.OracleXADataSource ---- for oracle
return basicManagedDataSource;

}
}


/**
*
*/

import javax.transaction.xa.Xid;

/**
* @author jijo
*
*/

public class MyXid implements Xid
{
protected int formatId;
protected byte gtrid[];
protected byte bqual[];

public MyXid()
{
}

public MyXid(int formatId, byte gtrid[], byte bqual[])
{
this.formatId = formatId;
this.gtrid = gtrid;
this.bqual = bqual;
}


public int getFormatId()
{
return formatId;
}

public byte[] getBranchQualifier()
{
return bqual;
}

public byte[] getGlobalTransactionId()
{
return gtrid;
}
}

No comments: