現在、ほとんどの appServer は JTA (Java Transaction Api) をサポートしています。これは、複数のオープン/クローズ JDBC 接続にまたがるトランザクションです。「threadLocal」の処理を行い、J2EE に準拠しています。フィルターで次のように使用します。
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
UserTransaction transaction = null;
try {
transaction = (UserTransaction)new InitialContext().lookup("java:comp/UserTransaction");
transaction.begin();
chain.doFilter(request, response);
transaction.commit();
} catch (final Exception errorInServlet) {
try {
transaction.rollback();
} catch (final Exception rollbackFailed) {
log("No ! Transaction failed !",rollbackFailed);
}
throw new ServletException(errorInServlet);
}
}
app-server で、jndi 名で Datasource を宣言し、それをコードで使用して接続を取得します (cx.commit()、cx.rollback()、または cx.setAutocommit() を作成しないでください。干渉します)。 JTAで)。同じ HTTP トランザクションで接続を数回開いたり閉じたりすることができます。JTA が処理します。
public void doingDatabaseStuff() throws Exception {
DataSource datasource = (DataSource)new InitialContext().lookup("/path/to/datasource");
Connection connection = datasource.getConnection();
try {
// doing stuff
} finally {
connection.close();
}
}