简体   繁体   中英

Hibernate session issue

When you first attempt to use a session Hibernate will create one and attach it to your local thread. When you commit the transaction in the session Hibernate will automatically close the session meaning it can't be reused. - got this quote from this site

how ever this is what my code looks like ,and i can i do close my hibernateSession every time i commited transaction:

Session session = HibernateUtil.getSessionFactory().openSession();
   session.setFlushMode(FlushMode.AUTO);
   session.beginTransaction();
   session.getTransaction().commit();
   session.close();

All of my code works fine, but there is issue : For example if i add row in to database,saving success,if i add another one after 1-10 seconds. Hibernate Exception occurs saying Session is closed. but this not happen if i add another one if i wait upto 1 minute. Is this somewhat wrong in my code or the server im connecting is slow(I do have this idea because updates on my java servlet code is sometimes delay)? Any idea?

You did a good thing by opening a session whenever you need to commit a transaction but:

In general hibernate manages all the session closing and opening for you, so if you need to take the responsibility on your shoulders you need to change the following in hibernate config file : hibernate.cfg.xml

Property Name: current_session_context_class
Property Value: managed

To create a session and start a transaction you need this code:

org.hibernate.classic.Session session = HibernateUtil.getSessionFactory().openSession();
session.setFlushMode(FlushMode.MANUAL);
ManagedSessionContext.bind(session);
session.beginTransaction();

And to commit a transaction do the following:

ManagedSessionContext.unbind(HibernateUtil.getSessionFactory()); 
session.flush(); 
session.getTransaction().commit(); 
session.close();

Where you can be 100% sure that whenever you commit you un-attach the session from your thread and the gc will take care of it.

So whenever you need to do another transaction you need to run the first part of the code again.

尝试使用.getCurrentSession()而不是openSession()

Instead of using

Session session = HibernateUtil.getSessionFactory().openSession();

use

Session session = HibernateUtil.getSessionFactory().getCurrentSession();

To automatically close session when transaction is committed set below property as true in you hibernate configuration

hibernate.transaction.auto_close_session=true

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