Hibernate API encapsulation and use in the business layer
Last Update:2018-07-24
Source: Internet
Author: User
To create, initialize, and invoke global sessionfactory instances, we use the Hibernateutil class to encapsulate the Hibernate API, reduce the writing of repetitive code, and make the program look more concise Package ... import ... public class Hibernateutil { private static L OG log = logfactory.getlog (Hibernateutil.class); private static configuration configuration; private static Sessionfactory sessionfactory; Static { try { configuration = new configuration (); sessiongfactory = Configuration. (). Configure (). Buildsessionfactory (); catch (Throwable ex) { Log.error (Ex.getmessage ()); throw new Exceptionininitializeerror (ex); } }   &NBSp public static Sessionfactory Getsessionfactory () { return sessionfactory; & nbsp; } public static Configuration GetConfiguration () { return configuration; } public static void Rebuildsessionfactory () { & nbsp; Synchronized (sessiongfactory) { try{ sessionffactory=getconfiguration (). Buildsessionfactory (); } catch (Exception ex) { log.error (Ex.getmessage ()); Throw Datastoreexception.datastoreerror (ex); } } } public static void Rebuildsessionfactory ( Configuration cfg) { Synchronized (sessiongfactory) { try{ sessionffactory= cfg.buildsessionfactory (); configuration = cfg; } catch (Exception ex) { log.error (Ex.getmessage ()); Throw Datastoreexception.datastoreerror (ex); } } public static void Close () { try{ sessionfactory.close (); catch (Exception ex) { Log.error (Ex.getmessage ()); } } //The following is the most commonly used session in the program to open, close, and rollback public static Session getsession () throws datastoreexception{ try { return sessionfactory.opensession (); }catch (Exception ex) { log.error (Ex.getmessage ()); throw Datastoreexception.datastoreerror (ex); } } public static void CloseSession (Session session) throws Datastoreexception { try{ session.close (); catch (Exception ex) { log.error (Ex.getmessage ()); throw Datastoreexception.datastoreerror (ex); } } public static void RollbackTransaction (Transaction Transaction) throws Datastoreexception { try{ if (transaction! = NULL) Transaction.rollback (); } catch (Exception ex) { log.Error (Ex.getmessage ()); Throw Datastoreexception.datastoreerror (ex); } }} Encapsulated use example: & Nbsp; session Session = Hibernateutil.getsession (); Transaction tx = NULL; try { tx = Session.begintransaction (); //hibernate Database Operations Query query = session.createquery ... & nbsp; Tx.commit (); } catch (Exception ex) { Hibernateutil.rollbacktransaction (ex); throw Datastoreexception.datastoreerror (ex);     } finally { hibernateutil.closesession (session) ; }