简体   繁体   中英

hibernate session scope error

I am working on a grails web-app

The application is running on a very slow network and is being accessed by old and slow client pc's that are running IE 6. The database connection is extremely slow and the db is over worked. So minimizing db calls and data being passed back and forth is a priority

I know that using session scope is not best practice. In this case i thought it would be best. Considering that all my pages require the same set of objects and this would have them fetched many times over

So i placed my object in the session scope session.obj = obj

It works fine with one issue Because the system is so slow multiple clicks on a link to a web page (controller/action) are possible.

When this happens i get a error on some cases org.hibernate.HibernateException: Illegal attempt to associate a collection with two open sessions

the error happens on this code

if (!obj?.isAttached()) {
   obj?.attach()
}

i have to attach the object back to the hibernate session so i can lazy load related objects i don't want to eager fetch (probably a solution) i seems that the error is cause when the object is being attached more then once. the condition does not seem to block the problem. Is it a race condition ?

i just would like to know if anyone has a solution to this problem or know the cause

thank you

If you want to avoid round-trips to the database and still code in a safe way, without having to deal with attaching/detaching objects to/from the Hibernate session, what you should do is use a Hibernate second-level cache. This would enable to transparently cache the often used entities, their associations, and even result of queries that are often executed.

The caching would also be more efficient and use less memory, because it would be shared across all the user sessions. And of course, it would be safer, because you wouldn't ever have stale entities in the HTTP session.

Definitely the way to go, IMO.

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