Connection is not associated with a managed connection.org.jboss.resource.adapter.jdbc.jdk6.WrappedConnectionJDK6

前端 未结 3 1887
梦毁少年i
梦毁少年i 2021-01-13 04:41

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.

3条回答
  •  有刺的猬
    2021-01-13 05:08

    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.

提交回复
热议问题