多线程异常:“将集合与两个打开的会话相关联的非法尝试"? [英] Multithreading Exception : "Illegal attempt to associate a collection with two open sessions"?

查看:104
本文介绍了多线程异常:“将集合与两个打开的会话相关联的非法尝试"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我试图在休眠中实现适当的多线程以进行保存和更新操作.我的每个线程都使用一个新创建的会话及其自己的事务.

So i was trying to implement proper multithreading for saving and update operation in hibernate. Each of my threads uses one newly created session with its own transaction.

我总是会收到将集合与两个打开的会话相关联的非法尝试".例外,因为im同时使用了多个会话(我也用一个共享的会话对其进行了测试,但这两个都不起作用).这里的问题是我需要多个会话,这就是告诉我休眠多线程可以工作的方式.

I always get a "Illegal attempt to associate a collection with two open session" exception, because im using multiple sessions at the same time ( I also tested it with a shared one, did not worked either ). The problem here is that i need multiple sessions, thats the way i was told hibernate multithreading would work.

该代码基本上在相同"位置在多个线程上执行.时间.

This code basically gets executed on multiple threads at the "same" time.

            var session = database.openSession();  // sessionFactory.openSession()
            session.beginTransaction();

            try {

                // Save my entities
                for (var identity : identities)
                    session.update(identity);

                session.flush();
                session.clear();
                session.getTransaction().commit();
            } catch (Exception e){
                GameExtension.getInstance().trace("Save");
                GameExtension.getInstance().trace(e.getMessage());
                session.getTransaction().rollback();
            }


            session.close();

那么我该如何解决这个问题?如何保持多个会话并同时防止该异常?

So how do i solve this issue ? How do i keep multiple sessions and prevent that exception at the same time ?

推荐答案

您面临的问题是,您向具有会话1的集合加载一个实体,然后以某种方式将此对象传递给会话2,而该对象仍处于关联状态进入开放会话1.即使在单线程环境中,这也根本行不通.

The issue you are facing is that you load an entity with a collection with session 1 and then somehow this object is passed to session 2 while the object is still associated to an open session 1. This simply does not work, even in a single threaded environment.

从会话1分离对象或在会话2中重新加载对象.

Either detach the object from the session 1 or reload the object in session 2.

这篇关于多线程异常:“将集合与两个打开的会话相关联的非法尝试"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆