The main research in this article is the closure of hibernate on session, as follows.
Student student = new Student(); student.setName("Jan"); student.setAge("22"); student.setAddress("Zhaoqing City, Guangdong Province"); Session session =HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); session.save(student); session.flush(); session.getTransaction().commit(); 1. What is the difference between getCurrentSession() and openSession()?
getCurrentSession() will be bound to the current thread, while the session created with openSession() will not begetCurrentSession() will be automatically closed when commit or rollback, while the session created with openSession() must be closed manually. 2. To use getCurrentSession() you need to add the following configuration to the hibernate.cfg.xml file:
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.current_session_context_class">jta</property>
What is the difference and correlation between openSession() and getCurrentSession() ?
When SessionFactory is started, Hibernate will create the corresponding CurrentSessionContext according to the configuration. When getCurrentSession() is called, the actual method to be executed is CurrentSessionContext.currentSession() . When currentSession() is executed, if the current Session is empty, currentSession will call openSession of SessionFactory. So getCurrentSession() is a better way to get Session for Java EE.
Many times session is close(); the reason is that you set it in hibernate.cfg.xml
<property name="hibernate.current_session_context_class">thread</property>
The system closes the session after commit(); after executing it. At this time, if you manually close the session, it will of course indicate an error.
The above is all the content of this article about the analysis of hibernate's closed instance on session, I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!