I am using Hibernate on a JBoss server. I get the error below.
The error happens when I try to connect to the database for the second time in the same sesssion.
This can happen when closing a connection, and afterwards using that connection again.
Imagine a scenario where for a bean call, at the start the connection is created and at the very end the connection is closed. The operation itself uses the connection, for all sorts of CRUD operations on a database. Somewhere during the operation the connection is closed and then used again.
In pseudo code:
try( Connection c = createConnection(); ) { // the very start
doOperations( c );
}
Now suppose somewhere in doOperations
you do something like:
void doOperations( Connection c ) {
String sql = ""; // an actual SQL statement
try( Connection c2 = c;
PreparedStatement ps = c2.prepareStatement( sql ); ) {
// ...
ps.executeUpdate( );
} // <<< the connection will be closed here
String sql2 = ""; // an actual SQL statement
try( PreparedStatement ps2 = c.prepareStatement( sql2 ); ) { // <<< exception thrown here, connection is already closed
// ...
}
}
The exception thrown is:
java.sql.SQLException: Connection is not associated with a managed connection.org.jboss.jca.adapters.jdbc.jdk6.WrappedConnectionJDK6@2cc0951e
at org.jboss.jca.adapters.jdbc.WrappedConnection.lock(WrappedConnection.java:154)
at org.jboss.jca.adapters.jdbc.WrappedConnection.prepareStatement(WrappedConnection.java:394)
Bottom line: don't close a Connection
and then use it again.