事务仍处于活动状态时无法关闭连接connection.close()上的异常

时间:2016-04-16 16:26:13

标签: java hibernate database-connection derby

我有一个方法可以创建与嵌入式Derby数据库的连接并对其执行选择查询。

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);
    }

以下是我的查询:

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 = ?

当我运行此代码时,我得到一个例外 JDBCException: java.sql.SQLException: Cannot close a connection while a transaction is still active.

但是当我关闭Connection.commit()或设置Connection autoCommit之前我致电true时(默认设置为false我{{1}对于我的Connection,它允许我成功关闭连接并获得所需的结果。

但我是否真的需要致电Connection进行commit()操作?有什么承诺?如果我不提交,那么某个地方是否存在未被释放的锁定?

post说我不应该这样做。我应该能够关闭我的连接,而不必提交或回滚。

我错过了什么?

1 个答案:

答案 0 :(得分:1)

如果您在autoCommit模式下,那么SELECT语句实际上是持有读锁,具体取决于您的隔离级别,因此提交{{1查询不仅仅是一个无操作。

是的,数据库没有变化,但提交仍然告诉数据库引擎您的事务已完成查看数据,因此它可以允许其他事务修改数据。

以下是一些背景资料:

  1. 隔离级别和并发性; https://db.apache.org/derby/docs/10.12/devguide/cdevconcepts15366.html
  2. 共享锁:https://db.apache.org/derby/docs/10.12/devguide/cdevconcepts842304.html
相关问题