UserTransaction with DataSource.getConnection() and DataSourceUtils.getConnection
<pre><code>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();
    }
  }
}
</code></pre>

<p>I am trying to compare <code>DataSource.getConnection()</code> and <code>DataSourceUtils.getConnection(DataSource)</code>, 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 <code>UserTransaction</code> (in current thread).</p>

<p>I saw the sample code above, I don't understand how come the example using <code>DataSource.getConnection</code>, which based on my understanding, we should always use <code>DataSourceUtils.getConnection(DataSource)</code> 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)</p>

<p>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?</p>

<p><strong><em>Edited</em></strong></p>

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