- 浏览: 14317 次
- 性别:
- 来自: 深圳
最新评论
HibernateUtil
- 博客分类:
- java
import javax.naming.InitialContext; import javax.naming.NamingException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hibernate.Interceptor; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.Environment; import org.hibernate.transaction.CMTTransactionFactory; /** * Hibernate 工具类 用于初始化Hibernate,并进行Session和Transaction的管理 */ public class HibernateUtil { private static Log log = LogFactory.getLog(HibernateUtil.class); private static final String INTERCEPTOR_CLASS = "hibernate.util.interceptor_class"; private static Configuration configuration; private static SessionFactory sessionFactory; private static boolean useThreadLocal = true; // 保存Session对象实例的线程局部变量 private static ThreadLocal threadSession = new ThreadLocal(); // 保存Transaction对象实例的线程局部变量 private static ThreadLocal threadTransaction = new ThreadLocal(); static { try { // 创建Configuration对象 configuration = new Configuration(); // 读取hibernate.properties或者hibernate.cfg.xml文件 configuration.configure(); // 指定一个全局的用户子定义的拦截器 String interceptorName = configuration .getProperty(INTERCEPTOR_CLASS); if (interceptorName != null) { Class interceptorClass = HibernateUtil.class.getClassLoader() .loadClass(interceptorName); Interceptor interceptor = (Interceptor) interceptorClass .newInstance(); configuration.setInterceptor(interceptor); } // 如果使用CMT,那么就不使用线程安全的Session和Transaction if (CMTTransactionFactory.class .getName() .equals( configuration .getProperty(Environment.TRANSACTION_STRATEGY))) { useThreadLocal = false; } if (configuration.getProperty(Environment.SESSION_FACTORY_NAME) != null) { // 绑定Hibernate到JNDI configuration.buildSessionFactory(); } else { // 使用静态的变量 sessionFactory = configuration.buildSessionFactory(); } } catch (Throwable ex) { // 必须捕获Throwable,否则不能捕获NoClassDefFoundError异常以及它的子类错误 log.error("Building SessionFactory failed!", ex); throw new ExceptionInInitializerError(ex); } } /** * 返回全局的SessionFactory对象的实例 * * @return SessionFactory */ public static SessionFactory getSessionFactory() { SessionFactory sf = null; String sfName = configuration .getProperty(Environment.SESSION_FACTORY_NAME); if (sfName != null) { log.debug("Looking up SessionFactory in JNDI."); try { sf = (SessionFactory) new InitialContext().lookup(sfName); } catch (NamingException e) { throw new RuntimeException(e); } } else { sf = sessionFactory; } if (sf == null) { throw new IllegalStateException("SessionFactory not available."); } return sf; } /** * 重新构建SessionFactory对象的实例 * */ public static void rebuildSessionFactory() { log.debug("Using current Configuration for rebuild"); rebuildSessionFactory(configuration); } /** * 使用指定的Configuration对象重新构建SessionFactory对象的实例 * * @param cfg */ public static void rebuildSessionFactory(Configuration cfg) { log.debug("Rebuilding the SessionFactory from given Configuration."); synchronized (sessionFactory) { if (sessionFactory != null && !sessionFactory.isClosed()) { sessionFactory.close(); } if (cfg.getProperty(Environment.SESSION_FACTORY_NAME) != null) { cfg.buildSessionFactory(); } else { sessionFactory = cfg.buildSessionFactory(); } configuration = cfg; } } /** * 关闭当前SessionFactory并且释放所有资源 * */ public static void shutdown() { log.debug("Shutting down Hibernate."); // 关闭缓冲和连接池 getSessionFactory().close(); // 清除静态变量 configuration = null; sessionFactory = null; // 清除本地进程变量 threadSession.set(null); threadTransaction.set(null); } /** * 获得当前Session对象的实例 * * @return Session */ public static Session getCurrentSession() { if (useThreadLocal) { Session s = (Session) threadSession.get(); if (s == null) { log.debug("Opening new Session for this thread."); s = getSessionFactory().openSession(); threadSession.set(s); } return s; } else { return getSessionFactory().getCurrentSession(); } } /** * 重新连接当前的Session * * @param session */ public static void reconnect(Session session) { if (useThreadLocal) { log.debug("Reconnecting Session to this thrwad."); session.reconnect(); threadSession.set(session); } else { log .error("Using CMT/JTA,intercepted not supported reconnect call."); } } /** * 断开当前Session * * @return Session the disconnected Session */ public static Session disconnectedSession() { if (useThreadLocal) { Transaction tx = (Transaction) threadTransaction.get(); if (tx != null && (!tx.wasCommitted() || !tx.wasRolledBack())) { throw new IllegalStateException( "Disconnecting Session but Transaction still open."); } Session session = getCurrentSession(); threadSession.set(null); if (session.isConnected() && session.isOpen()) { log.debug("Disconnecting Session from this thread."); session.disconnect(); } return session; } else { log .error("Using CMT/JTA,intercepted not supported disconnect call."); return null; } } /** * 关闭Session对象 * */ public static void closeSession() { if (useThreadLocal) { Session s = (Session) threadSession.get(); threadSession.set(null); Transaction tx = (Transaction) threadTransaction.get(); if (tx != null && (!tx.wasCommitted() || !tx.wasRolledBack())) { throw new IllegalStateException( "Closing Session but Transaction still open."); } if (s != null && s.isOpen()) { log.debug("Closing Session of this thread."); s.close(); } } else { log.warn("Using CMT/JTA,intercepted superfluous close call."); } } /** * 开始一个新的数据库事务 * */ public static void beginTransaction() { if (useThreadLocal) { Transaction tx = (Transaction) threadTransaction.get(); if (tx == null) { log.debug("Starting new database transaction in this thread."); tx= getCurrentSession().beginTransaction(); threadTransaction.set(tx); } } else { log.warn("Using CMT/JTA,intercepted superfluous tx begin call."); } } /** * 提交数据库事务 * */ public static void commitTransaction() { if (useThreadLocal) { try { Transaction tx = (Transaction) threadTransaction.get(); if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()) { log .debug("Committing database transaction of this thread."); tx.commit(); } threadTransaction.set(null); } catch (RuntimeException e) { log.error(e); rollbackTransaction(); throw e; } } else { log.warn("Using CMT/JTA,intercepted superfluous tx commit call."); } } /** * 回滚数据库事务 * */ public static void rollbackTransaction() { if (useThreadLocal) { Transaction tx = (Transaction) threadTransaction.get(); try { threadTransaction.set(null); if (tx != null && !tx.wasCommitted() && !tx.wasRolledBack()) { log .debug("Trying to rollback database transaction of this thread."); tx.rollback(); } } catch (RuntimeException e) { throw new RuntimeException( "Migth swallow original cause,check Error log!", e); } finally { closeSession(); } } else { log.warn("Using CMT/JTA,intercepted superfluous tx rollback call."); } } }
相关推荐
HibernateUtil 分页 增删改查 封装 HibernateUtil 分页 增删改查 封装 HibernateUtil 分页 增删改查 封装
HibernateUtil分装完整版HQL查询HibernateUtil分装完整版HQL查询
06_传智播客hibernate教程_完善HibernateUtil类及hql查询入门
hibernate入门实例封装了HibernateUtil,完成数据库的添加操作,和查询操作。 Session的save方法和get方法。
HibernateUtil工具类
Hibernate5.2.1 的工具类 创建session 和 sessionFactory
HibernateUtil.java HibernateUtils.java HttpRequester.java HttpRespons.java HttpUtil.java MD5Util.java Pagination.java PropertiesUtil.java RegUtil.java StringUtil.java UploadUtil.java UUIDUtils.java
欢迎大家咨询,我会尽量去与大家讲解,希望对你们有所帮助
} <br> public String createPasswordTicket(User user) { HibernateUtil.executeUpdate( "delete from PasswordTicket as pt where pt.user=?", new Object[] { user } ); String ...
SessionFactory factory = HibernateUtil.getSessionFactory(); Session session = factory.openSession(); Serializable id = null; Transaction tran = null; try{ tran = session.beginTransaction(); ...
生成HibernateSessionFactory工具类(HibernateUtil) ===利用Myeclipse根据表生成实体类和映射文件=== g.进入DB Browser窗口,找到数据表 h.数据表右键,选择Hibernate reverse Engin... i.选择要生成的文件hbm....
2、采用Jsp->Action->Service->Dao的编码方式,封装了HibernateUtil、SpringUtil、HqlUtil等工具,以及简化了增删查改操作。 3、此底层包含泛型DAO、Proxool连接池、国际化语言、DateUtil工具、ExcelUtil报表工具、...
06_完善HibernateUtil类及hql查询入门 07_实体类或属性名与数据库关键字冲突问题 10_使用Hibernate完成CRUD实验的步骤说明 11_完成CRUD实验并回顾和补充细节知识(上) 12_完成CRUD实验并回顾和补充细节知识(下...
(2)dao 使用了公共的GenricDao接口及实现类GenricHibernateDao 并使用了泛型 com.chen.common 包中的CopyOfGenericHibernateDao.java HibernateUtil.java两个是在集成Spring前使用的 可以当做参考吧; (3) ...
│ │ HibernateUtil.java │ │ UsersDAO.java │ │ │ └─entity │ BillEntity.java │ GoodsListEntity.java │ └─WebRoot │ index.jsp │ ├─img │ dn1.jpg │ dn2.jpg │ dn3.jpg │...
HibernateUtil タ・ <br>ミツスィメサタ・HibernateUtil」ャモヲクテハヌクコヤテ hibernate マ犹リイルラ」 ユ簑・メハヌエモヤュタエオトケ、ウフヨミスォホトシヨアスモソスアエタエモテ。」 ...
hibernate 一对多测试工程,博客介绍请参照: http://blog.csdn.net/smilefyx/article/details/48596665