您的位置:首页 > 其它

org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl@10cf3d8 is closed。

2016-12-08 17:26 309 查看
描述:在使用hibernate操作数据库时报org.hibernate.resource.jdbc.internal.LogicalConnectionManagedImpl@10cf3d8 is closed。
启动程序后,首先执行了一个get,然后接着执行update是抛出上该异常。 

原因:
操作Transaction时使用了ThreadLocal.在beginTransaction时,将新的transaction   set到了ThreadLocal中。
由于在get时执行beginTransaction打开了一个事务,而未执行commitTransaction方法,导致事务未提交。
所以接下来的update时抛了异常。

解决方法:
get时不需要commit,所以不可以调用commitTransaction方法,单独写一个提交事务的方法,把ThreadLocal中的事务重置即可。

代码:
private static final ThreadLocal<Transaction> transactionThreadLocal = new ThreadLocal<Transaction>();

public static void beginTransaction() {  

        Transaction transaction = (Transaction) transactionThreadLocal.get();  

      

        try {  

         

            if (transaction == null) {  

                transaction = getSession().beginTransaction();  

                transactionThreadLocal.set(transaction);  

            }  

        } catch (HibernateException e)  {  

            throw new HibernateException(e);  

        }  

    }  

    

    public static void commitTransaction() {  

        Transaction transaction = (Transaction) transactionThreadLocal.get();  

         

        try {

            if (transaction != null) {  

                transaction.commit();  

            }  

            transactionThreadLocal.set(null);  

        } catch (HibernateException e) {  

            throw new HibernateException(e);  

        }  

    }

    public static void commitNullTransaction() {
Transaction transaction = (Transaction) transactionThreadLocal.get();  

        

        try {  

        if (transaction != null) {

         transactionThreadLocal.set(null); 

        }

        } catch (HibernateException e) {  

            throw new HibernateException(e);  

        }  
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  hibernate
相关文章推荐