Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

java - Multithreading Exception : "Illegal attempt to associate a collection with two open sessions"?

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.

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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...