GMsoF GMsoF - 2 months ago 8
Java Question

UserTransaction with DataSource.getConnection() and DataSourceUtils.getConnection

static void clean() throws Exception {
final UserTransaction tx = InitialContext.doLookup("UserTransaction");
tx.begin();

try {
final DataSource ds = InitialContext.doLookup(Databases.ADMIN);
Connection connection = ds.getConnection();//line 1
connection = ds.getConnection(); //line 2- call again for testing purpose
PreparedStatement st = connection.prepareStatement("xxxxxxx sql script");
st.executeUpdate();
st.close();
connection.close();
tx.commit();
} finally {
if (tx.getStatus() == Status.STATUS_ACTIVE) {
tx.rollback();
}
}
}


I am trying to compare
DataSource.getConnection()
and
DataSourceUtils.getConnection(DataSource)
, according to the Javadoc, the first one always get a new connection and second one always get a current connection that bind to the active
UserTransaction
(in current thread).

I saw the sample code above, I don't understand how come the example using
DataSource.getConnection
, which based on my understanding, we should always use
DataSourceUtils.getConnection(DataSource)
instead of other, because we want to commit the whole chunk of scripts in a connection instead of having more than one connection. (correct me if I am wrong)

I don't understand why, so I added a duplicated line to test (line 2), can anyone explain how this thing work in background if there is without line 2 and with line 2? What is the difference?

Edited

Based on the Javadoc,
DataSource.getConnection()
is not even able to attach the connection to the active
Usertransaction
, how does the
UserTransaction
internally set the connection's
autoCommit(false)
?

Answer

I have a similar question, which already answered in here.

As long as the calling is inside transaction context and we are using DataSource to obtain the connection, it is smart enough to always return the only active connection. I think it is related to the implementation of the transaction manager and the DataSource, which for my case, both I have fetched from Weblogic via JNDI.

Comments