Hibernate's understanding of openSession and getCurrentSession for Session management

The reason is that the project background timer starts the query, and it cannot connect to the database every time it reaches a certain time: after a few days of searching, it is found that in the project dao layer, the method for the user to obtain the session is this.getHibernateTemplate().getSessionFactory(). openSession ().createSQLQuery(sql); 

openSession does not automatically close the session when creating a session

1: getCurrentSession will associate the Session with the current thread, and openSession just reopens a Session

2: The Session obtained by getCurrentSession will be automatically closed when the transaction is closed or rolled back, while the Session obtained by openSession must be closed manually

     getCurrentSession, which is used by specific implementations to track the current context session, Hibernate has two built-in implementations of this interface

   * org.hibernate.context.JTASessionContext -- the current session is tracked and defined by the currently executing thread

   * org.hibernate.context.ThreadLocalSessionContext -- the current thread is tracked and delimited by the currently executing thread

 Both implementations provide a programming model of "one session per database transaction", also known as one session per request, and the start and end of a Hibernate session is controlled by the existence of a database transaction.


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325658462&siteId=291194637