Session: is a session between the application and the database, the center of Hibernate operation and the basis of persistence layer operations. The life cycle of objects/transaction management/database access are closely related to Session.
The Session object is built through the SessionFactory. Here is an example to introduce two ways to obtain sessions by Hibernate.
Logs are a very common concern in programming. When users operate on databases, they need to record this series of operations to track the dynamics of the database. So when a user inserts a record into the database, they have to record a record in the log file. The user's series of operations must be carried out in a session, otherwise this will become two threads. There is no guarantee of synchronization. Look at the following code
HibernateUtil Management Session Tools
package com.bjpowernode.usermgr.util;import org.hibernate.Session;//hibernate3's import org.hibernate.SessionFactory;import org.hibernate.cfg.Configuration;public class HibernateUtils {private static SessionFactory factory;static{try{//Read hibernate.cfg.xml file Configuration cfg=new Configuration().configure();//Create SessionFactory factory=cfg.buildSessionFactory();}catch(Exception e){e.printStackTrace();}}//Get the open Session public static Session getSession(){return factory.openSession();}//Close Session public static void closeSession(Session session){if(session!=null){if(session.isOpen()){session.close();}}} public static SessionFactory getSessionFactory(){return factory;}}}User business logic layer
package com.bjpowernode.usermgr.manager;import java.util.Date;import org.hibernate.Session;import com.bjpowernode.usermgr.domain.Log;import com.bjpowernode.usermgr.domain.User;import com.bjpowernode.usermgr.util.HibernateUtils;public class UserManagerImpl implements UserManager {/** * Both adding users and adding logs use the same Session, so * When adding users fails, logs will also fail. Transaction rollback* User adds success logs and will also add success*/public void addUser(User user) {Session session=null;try{//Get the current thread Session session=HibernateUtils.getSessionFactory().getCurrentSession();session.beginTransaction();//Save user session.save(user);Log log=new Log();log.setType("Operation Log");log.setTime(new Date());log.setDetail("XXX");LogManager logManager=new LogManagerImpl();//Save logs logManager.addLog(log);session.getTransaction().commit();}catch(Exception e){e.printStackTrace();session.getTransaction().rollback();}}}Log implementation class:
package com.bjpowernode.usermgr.manager;import org.hibernate.Session;import com.bjpowernode.usermgr.domain.Log;import com.bjpowernode.usermgr.util.HibernateUtils;public class LogManagerImpl implements LogManager {public void addLog(Log log) {//Get Session of the current thread HibernateUtils.getSessionFactory().getCurrentSession().save(log);}}Test class
package com.bjpowernode.usermgr.manager;import junit.framework.TestCase;import com.bjpowernode.usermgr.domain.User;public class UserManagerImplTest extends TestCase {public void testAddUser() {UserManager userManager=new UserManagerImpl();User user=new User(); user.setName("Zhang San"); userManager.addUser(user); }Notice:
1. What is the difference between openSession and getCurrentSession?
*openSession must be closed, currentSession will be closed automatically after the transaction is completed.
*openSession is not bound to the current thread, currentSession is bound to the current thread
2. If you use currentSession, you need to configure it in the hibernate.cfg.xml file:
*If it is a local transaction (jdbc transaction)
<propertyname="hibernate.current_session_context_class">thread</property>
*If it is a global transaction (jta transaction)
<propertyname="hibernate.current_session_context_class">jta</property>
Global Transactions: Transactions managed and coordinated by the Explorer that can span multiple databases and processes. The resource manager generally uses the XA two-stage submission protocol to interact with the "Enterprise Information System" (EIS) or database.
Local transactions: transactions local to a single EIS or database and restricted to a single process. Local transactions do not involve multiple data sources.
Summarize
The above is the entire content of this article about the two code examples of obtaining Session in Hibernate. I hope it will be helpful to everyone. Interested friends can continue to refer to:
Analysis of the instance of adding, deleting, revising and searching through session
Quickly learn about Session in Hibernate
Hibernate uses hbm.xml to configure mapping relationship analysis
If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!