Code examples of two ways to obtain session in Hibernate
Session: it is a session between an application and a database. It is the center of Hibernate operation and the basis of persistence layer operation Object life cycle, transaction management and database access are closely related to session
The session object is built through sessionfactory. The following is an example to introduce hibernate's two methods of obtaining sessions.
Logging is a common concern in programming Users need to record this series of operations in order to track the dynamics of the database When a user inserts a record into the database, a record must be recorded in the log file. A series of user operations must be carried out in one session, otherwise it will become two threads Synchronization cannot be guaranteed Look at the code below
Hibernateutil tool class for managing session
User business logic layer
Log implementation class:
Test class
be careful:
1. What is the difference between opensession and getcurrentsession?
*Opensession must be closed. Currentsession will be closed automatically after the transaction ends
*Opensession is not bound to the current thread, while currentsession is bound to the current thread
2. If currentsession is used, it needs to be in hibernate cfg. XML file:
*If it is a local transaction (JDBC transaction)
*If it is a global transaction (JTA transaction)
Global transactions: transactions managed and coordinated by the resource manager, which can span multiple databases and processes. Resource managers generally use XA two-phase submission protocol to interact with enterprise information system (EIS) or database.
Local transactions: transactions that are local to a single EIS or database and limited to a single process. Local transactions do not involve multiple data sources.
summary
The above is all about the code examples of the two ways to obtain session in hibernate. I hope it will be helpful to you. Interested friends can continue to see:
Hibernate implements the analysis of adding, deleting, modifying and querying operation examples through session
Quickly learn about session in Hibernate
Hibernate uses HBM XML configuration mapping relation parsing