Repost - the maintenance of the Hibernate session

xiaoxiao2021-03-06  51

HibernateUit, specializes in Hibernate session maintenance, its code is as follows: package com.huangdong.demo.util; import.sf.hibension; import net.sf.hibernate.Session; import net.sf.hibernate .SessionFactory; import net.sf.hibernate.cfg.Configuration; public class HibernateUtil {private static final SessionFactory sessionFactory; static {try {sessionFactory = new Configuration () configure () buildSessionFactory ();..} catch (HibernateException ex) { throw new RuntimeException ( "Exception building SessionFactory:" ex.getMessage (), ex);}} public static final ThreadLocal session = new ThreadLocal (); public static Session currentSession () throws HibernateException {Session s = (Session) session. GET (); // Open a new session, if this thread has none yet if (s == null) {s = sessionFactory.opensesis (); session.set (s);} return s;} public static void CloseSession "throws hibernateException {session s = (session) session.get (); session.set (null); if (s! = null) s.close ();}} Above we need to pay attention to this code The content is meticulous. First, there are two objectives of this class: single example: use a unique sessionFactory instance in the system. The main reason One is that Factory only needs an instance to call the method; on the other hand, the time takes the sessionFactory takes for too long, and each time it is instantiated, it will excessively wast the system CPU resources. Each line and the corresponding database connection session: here is a local variable to each thread to achieve this.

Plugin requires a single instance by the solid line is to rely on what does the following code: private static final SessionFactory sessionFactory; static {try {sessionFactory = new Configuration () configure () buildSessionFactory ();} catch (HibernateException ex) {throw.. New runtimeException ("Exception Building SessionFactory:" EX.GetMessage ();}} A local static variable sessionFactory is the only instance of the entire Application used, which transferred in the class for the first time by sessionFactory = New CONFIGURATION (). CONFIGURE (). BuildSessionFactory (); instantiate yourself. This instantiated process is longer. Obviously, this operation is similar to usually what we can do when we use servlet to initialize the initial in the servlet to transfer in memory. The PLUGIN is provided in Struts to expand the basic function of Struts. In fact, the implementation of Plugin is also based on servlet's init methods and Destory methods. Summary, that is, in this special environment in this special environment, it is Struts (because the servlet it is just one, or only a class and the subclass of the class) we can use the servlet's init / destory mechanism ( That is, the PLUGIN mechanism is to complete the sessionFactory initialization and the WEB application stop when the WEB application is started. But at the same time, it will also be found that if the sessionFactory is instantiated in PLUGIN, it cannot be transferred to the user, but the Web application environment can also be used to use the following solution: JNDI Plugin's static method / variable servletContex T Attribute Let's describe the modes used by these sessionFactory using JNDI.

Plugin to JNDI The idea of ​​the initialization of sessionFactory through JNDI is basically like this: In the initialization of the instance of the sessionFactory in a plugin, it returns the SESSIONFACTORY instance bind to the JNDI directory tree. On a node of the tree. Get the specific session of SessionFactory with sessionFactory to get the specific session in the Destion method of the Plugin is the unbind node, and clear the instance of the sessionFactory is the specific code snippet, first we look at the related code in Plugin: / * * create date 2003-12-26 * / package com.huangdong.demo.plugin; import javax.naming.Context; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.servlet.ServletException; import net.sf.hibernate.HibernateException; import net.sf.hibernate.SessionFactory; import net.sf.hibernate.cfg.Configuration; import org.apache.struts.action.ActionServlet; import org.apache.struts.action.PlugIn; import org.apache.struts.config.ModuleConfig; / ** * @author HD * / public class InitHibernate implements plugIn {private Context ctx; private SessionFactory sessionFactory; / * * widget destruction methods * / public void destroy () {if ( CTX! = null) {Try {// unbind JNDI Node CTX.unbind ("HibernateSessionFactor y ");} catch (namingexception e) {E.PrintStackTrace ();}} f (sessionFactory! = null) {Try {// Close sessionFactory sessionFactory.Close ();} catch (hibernateException E) {E.PrintStackTrace );} sessionFactory = null;}} / * * widget initializer * / public void init (ActionServlet servlet, ModuleConfig config) throws ServletException {try {// Get an instance of SessionFactory sessionFactory = new Configuration () configure () buildSessionFactory.. ();} catch (HibernateException ex) {throw new RuntimeException ( "Exception building SessionFactory:" ex.getMessage (), ex);} try {// container made context ctx = new InitialContext (); // the sessionFactory bind CTX.bind in JND tree ("HibernateSessionFactory"

, SessionFactory);} catch (NamingException ex) {throw new RuntimeException ( "Exception binding SessionFactory to JNDI:" ex.getMessage (), ex);}}} Next we look at the transformation of the original HibernateUitl class, we create a new HibernateUtilPlus Class: / * * Create Date 2003-12-28 * * / package com.huangdong.demo.util; import javax.naming.context; import javax.naming.initialcontext; import javax.naming.namingexception; import net.sf. hibernate.HibernateException; import net.sf.hibernate.Session; import net.sf.hibernate.SessionFactory; / ** * @author HD * / public class HibernateUtilPlus {private static SessionFactory sessionFactory = null; public static final ThreadLocal session = new ThreadLocal (); public static Session currentSession () throws HibernateException {if (sessionFactory == null) {// If sessionFactory instance is null if acquired from the JNDI (getSystemSessionFactory () == false) {throw new HibernateException ( "Exception geting sessionFactory "}}} session s = (session) session.get (); // Open a new session, IF this thread has none yetiff (s == NULL) {s = sessionFactory.opensession (); session.set (s);} returnit s;} spreadion hibernateException {session s = (session) session.get (); session.set NULL); if (s! = null) s.close ();} private static boolean getSystemSessionFactory () {Try {// From JNDI to acquire sessionFactory instance, if an error returns false consttex = new initialcontext (); sessionFactory = ("HibernateSessionFactory);} Catch (Namingexception E) {Return False;} Return true;}} There is a getSystemSessionFactory method to get an instance of SessionFactory from JNDI.

We still use the previous testservlet to test, the TestServlet class later is as follows: / * * Create a date 2003-12-26 * * / package com.huangdong.demo.bean; import java.util.calendar; import net.sf. hibernate.HibernateException; import net.sf.hibernate.Session; import net.sf.hibernate.Transaction; import com.huangdong.demo.dao.SysUser; import com.huangdong.demo.util.HibernateUtilPlus; / ** * @author HD * / public class TestHibernate {public TestHibernate () {} public boolean testAdd () {try {Session session = HibernateUtilPlus.currentSession (); Transaction tx = session.beginTransaction (); SysUser user = new SysUser (); user.setUsername ("丫 2"); User.SetUserPasword ("UHKUHKQEPDWQI"); User.SetLastLogin (Calendar.GetInstance ()); session.save (user); tx.commit (); hibernateutilplus.closesis ();} catch HibernateException E) {E.PrintStackTrace (); return false;} Return true;}} This uses the HibernateUtilPlus class to get session. Finally, we need to configure a written plugin to Struts to let the application server starts to identify the presence of this plugin to initialize the relevant content.

There is a configuration file called Struts-Config.xml under the web-INF folder, where adds Plugin configuration: Add Plugin configuration, use the plug-in element to explain -> Run Tomcat again to test. You can download the Eclipse example of JNDI PLUGIN here. Another two ways to explore the most beginning of the article, we mentioned three ways, in addition to the other two: Plugin's static method / variable servletContext Attribute here, we will briefly explain these two methods The principle is not actually completed. The specific code and tests also ask the reader to complete it. Plugin's static method and variable use this method similar to the principle of using the original Hibernateutil class, but can instantiate the sessionFaction in the init method.

As follows: / * * Create Date 2003-12-26 * / package com.huangdong.demo.plugin; import javax.servlet.ServletException; import net.sf.hibernate.HibernateException; import net.sf.hibernate.SessionFactory; import net .sf.hibernate.cfg.configuration; import org.apache.struts.action.ActionServlet; import org.apache.struts.action.plugin; import org.apache.struts.config.Moduleconfig; / ** * @Author hd * / public class InitHibernate implements plugIn {public static final SessionFactory sessionFactory; / * * widget destruction methods * / public void destroy () {sessionFactory = null;}} / * * widget initializer * / public void init (ActionServlet servlet, ModuleConfig config ) throws ServletException {try {// Get an instance of SessionFactory sessionFactory = new Configuration () configure () buildSessionFactory ();} catch (HibernateException ex) {throw new RuntimeException ( "Exception building SessionFactory:".. ex.getMessage () , EX);}}} This PLUGIN code is very simple. It also uses this Plugin's public variable directly to obtain the sessionFactroy instance. The principle of the Attribute of servletContext is based on the use of servlet, and uses trouble in Struts. Its principle is this: first initialize the SessionFactory instance in Plugin, use these two sentences to put it in the servlet's context = servlet.getServletContext (); context.settribute ("sessionFactory, sessionFactory); The method used is very simple. It is to extend a custom ActionServlet. Before submitting the specific Action, extract the sessionFactory, put into the parameter request of the EXECUTE method that calls the action. Code is as follows: ServletContext context = servlet.getServletContext (); context.getAttribute ( "SESSIONFACTORY", sessionFactory); request.setAttribute ( "SESSIONFACTORY", sessionFactory); in such a method in particular can execute: request.getAttribute ( "SESSIONFACTORY ", sessionFactory; come to the correct sessionFactory.

转载请注明原文地址:https://www.9cbs.com/read-87482.html

New Post(0)