1. The difference between opensession and getcurrentsession
Package com.rk.hibernate.cache;import org.hibernate.session;import org.hibernate.sessionfactory ; import org.hibernate.cfg.configuration;import org.junit.test;public class app_ Sessioninproject{private static sessionfactory sf;static{sf = new configuration ( ). Configure (). addclass (Department.class). addclass (Employee.class). Buildsessionfactory (); @Testpublic void testsession () {//opensession: Create a session, each time a new sessionsession is created session1 = sf.opensession (); Session session2 = sf.opensession (); System.out.println (Session1 == session2); Session1.close (); Session2.close ();//getcurrentsession Create or get a session// thread to create session // be sure to configure: <property name= "hibernate.current_session _context_class ">thread</property>session session3 = sf.getcurrentsession (); Session session4 = sf.getcurrentsession (); System.out.priNtln (SESSION3&NBSP;==&NBSP;SESSION4);// close "thread-created session, can not close; thread end session Auto Close"// Session3.close ();//session4.close (); error, because the same session is closed! }}
2. Use Hibernate Session in Strut2 project
Hibernate.cfg.xml
<! Doctype hibernate-configuration public "-//hibernate/hibernate configuration dtd 3.0// EN "Http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd" >Hibernateutils.java
Package Com.rk.utils;import Org.hibernate.session;import Org.hibernate.sessionfactory;import Org.hibernate.cfg.configuration;public class Hibernateutils {//Initialize sessionfactoryprivate static sessionfactory SF; static {SF = new Configuration (). Configure (). Buildsessionfactory ();} Create (GET) Sessionpublic static session getsession () {//thread the way the session was created, must be configured//Can not be closed, will automatically shut down. return sf.getcurrentsession ();}}
Sessioninterceptor.java
package com.rk.interceptor;import org.hibernate.session;import com.rk.utils.hibernateutils; import com.opensymphony.xwork2.actioninvocation;import Com.opensymphony.xwork2.interceptor.abstractinterceptor;/** * session Management Interceptor: * When you access the action, create a session; * action ---> service --> dao "Get the session created here" * * */public class sessioninterceptor extends abstractinterceptor {@Overridepublic string intercept (actioninvocation invocation) throws Exception {try {// 1. Create sessionsession session = First Hibernateutils.getsession ();// 2. open transaction session.begintransaction ();// 3. Execute actionstring result = invocation.invoke ();// 4. Commit Transaction session.gettransaction (). Commit (); // do not need to close session// return result view return result;} catch (Exception e) {e.printstacktrace ();return "error";}}}
Departmentdao.java
Package Com.rk.dao;import Com.rk.entity.dept;import Com.rk.utils.hibernateutils;public class DepartmentDao {/** * primary key query */public Department FindByID (int id) {//Gets session, executes operation return (Department) hibernateutils.getsession (). Get ( Department.class, id);}}
3, Hibernateutil.java
package com.rk.hibernate.utils;import org.hibernate.hibernateexception;import Org.hibernate.session;import org.hibernate.sessionfactory;import org.hibernate.transaction;import org.hibernate.cfg.configuration;public class hibernateutil{private static final sessionfactory sf;private static final threadlocal<session> threadsession = new ThreadLocal<Session> ();p rivate static final threadlocal< Transaction> threadtransaction = new threadlocal<transaction> (); static{ Configuration cfg = new configuration (); Sf = cfg.configure (). buildSessionFactory ();} Public static session getsession () {session session = threadsession.get (); try{// Open a new Session, if this thread has none yetif ( Session == null) {Session = sf.opeNsession (); Threadsession.set (session);}} catch (hibernateexception e) {throw new runtimeexception (e);} Return session;} Public static void closesession () {try{session session = threadsession.get (); Threadsession.set (NULL);if (Session != null && session.isopen ()) { Session.close ();}} catch (hibernateexception e) {throw new runtimeexception (e);}} Public static void begintransaction () {transaction tx = threadtransaction.get (); try{if (tx == null) {tx = getsession (). BeginTransaction (); Threadtransaction.set (tx);}} catch (hibernateexception e) {throw new runtimeexception (e);}} Public static void committransaction () {transaction tx = threadtransaction.get (); try{if (tx != null && !tx.wascommitted () && ! Tx.wasrolledback ()) {tx.commit (); threadtransaction.Set (null);}} catch (hibernateexception e) {rollbacktransaction ();}} Public static void rollbacktransaction () {Transaction tx = threadtransaction.get ( );try{if (tx != null && !tx.wascommitted () && ! Tx.wasrolledback ()) {threadtransaction.set (null); Tx.rollback ();}} catch (Hibernateexception ex) {throw new runtimeexception (ex);} Finally{closesession ();}}}
Filter filters
public void DoFilter (ServletRequest request,servletresponse response,filterchain chain) throws IOException, Servlet Exception {try {chain.dofilter (request, response); Hibernateutil.committransaction (); } finally {hibernateutil.closesession (); }}
DAO
public void Execute () {//Get values from request try {hibernateutil.begintransaction (); Session session = Hibernateutil.getsession (); Forward to success.jsp page} catch (Hibernateexception ex) {throw new Infrastructureexception (ex); } catch (Exception ex) {//Throw application specific Exception}}
(21) How Hibernate session is managed in the project