HibernateSession 浅浅的花香味﹌ 2022-06-18 01:39 56阅读 0赞 public class HibernateSession { private static final ThreadLocal sessionThread = new ThreadLocal(); private static final ThreadLocal transactionThread = new ThreadLocal(); private static SessionFactory sf = null; public static void setSessionFactory(SessionFactory _sf) { sf = _sf; } public static boolean isSessionCreated() { return (sessionThread.get() != null); } public static boolean isTransactionCreated() { return (transactionThread.get() != null); } /** * Current Session * * @return Session * @throws HibernateException */ public static Session currentSession() throws HibernateException { Session s = (Session) sessionThread.get(); if (s == null) { if (sf == null) sf = new Configuration().configure().buildSessionFactory(); s = sf.openSession(); sessionThread.set(s); } return s; // return sf.getCurrentSession(); } /** * Get a new Session * * @return Session * @throws HibernateException */ public static Session newSession() throws HibernateException { if (sf == null) sf = new Configuration().configure().buildSessionFactory(); return sf.openSession(); } /** * Start or Add current Session's Transaction * * @return Transaction * @throws HibernateException */ public static Transaction currentTransaction() throws HibernateException { Transaction tx = (Transaction) transactionThread.get(); if (tx == null) { tx = currentSession().beginTransaction(); transactionThread.set(tx); } return tx; } /** * Commit * * @throws HibernateException */ public static void commitTransaction() throws HibernateException { Transaction tx = (Transaction) transactionThread.get(); transactionThread.set(null); if (tx != null) tx.commit(); } /** * Rollback * * @throws HibernateException */ public static void rollbackTransaction() throws HibernateException { Transaction tx = (Transaction) transactionThread.get(); transactionThread.set(null); if (tx != null) tx.rollback(); } /** * Close Session * * @throws HibernateException */ public static void closeSession() throws HibernateException { Session s = (Session) sessionThread.get(); sessionThread.set(null); if (s != null && s.isOpen()) { try { s.close(); } catch (Exception e) { } } // if (sf != null) { // sf.getCurrentSession().close(); // } } public static void main(String[] args) { try { String conf = "hibernateTest.cfg.xml"; if (args.length != 0) conf = args[0]; Configuration cfg = new Configuration().configure("/" + conf); SchemaExport se = new SchemaExport(cfg); se.setOutputFile("create_table.sql"); se.create(true, true); } catch (HibernateException e) { System.out.println(e.getMessage()); } } }
相关 HibernateSession public class HibernateSession { private static final ThreadLocal sessionTh 浅浅的花香味﹌/ 2022年06月18日 01:39/ 0 赞/ 57 阅读
还没有评论,来说两句吧...