简体   繁体   中英

Cannot close a connection while a transaction is still alive Exception on connection.close()

I have a method that creates a Connection with Embedded Derby Database and performs a Select query on it.

public PersonMID findPersonMID(String personAlias, CodeUID aliasTypeCodeUID, LogicalDomainMID logicalDomainMID) throws SQLException
{
    Connection connection = getConnection();

    try
    {
        QueryExecutor<Long> findPersonIdByPersonAliasExecutor = FindPersonIdByPersonAliasDelegate.getExecutor(authority,connection, personAlias);

        Long result = findPersonIdByPersonAliasExecutor.execute();

        if(result == null)
        {
            return null;
        }
        return PersonMID.create(authority, result);
    }
    finally
    {
        JDBCAssistant.close(connection);
    }

Here is what my query looks like:

select P.PRSON_ID from PRSON_ALIAS PA join PRSON P on P.PRSON_ID = PA.PRSON_ID and P.LOGICAL_DOMAIN_ID = ? where PA.PRSON_ALIAS_TYPE_CD = ? and    PA.ALIAS = ?

When I run through this code, I get an Exception JDBCException: java.sql.SQLException: Cannot close a connection while a transaction is still active.

But when I call Connection.commit() before I close the Connection or set autoCommit true (it is set to false by default for my Connection ) for my Connection , it is allowing me to successfully close the connection and get the reqired result.

But do I really need to call commit() for a Select operation? What's there to commit? Is there a lock somewhere that is not being released if I dont commit?

This post says I shouldn't have to do it. I should be able to close my connection without having to commit or rollback.

What am I missing?

If you are not in autoCommit mode, then a SELECT statement is in fact holding read locks, depending on your isolation level, and so committing a SELECT query is more than a no-op.

Yes, there is no change to the database, but the commit still tells the database engine that your transaction is finished looking at the data, and it can therefore allow other transactions to modify the data.

Here's some background material:

  1. Isolation levels and concurrency; https://db.apache.org/derby/docs/10.12/devguide/cdevconcepts15366.html
  2. Shared locks: https://db.apache.org/derby/docs/10.12/devguide/cdevconcepts842304.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM