zoukankan      html  css  js  c++  java
  • Hibernate的一个帮助类感觉写得比较好,有参考价值,果断备份下来……

     1 package cn.zj.qiao.utils;
     2 
     3 import org.hibernate.HibernateException;
     4 import org.hibernate.Session;
     5 import org.hibernate.SessionFactory;
     6 import org.hibernate.cfg.Configuration;
     7 import org.hibernate.service.ServiceRegistry;
     8 import org.hibernate.service.ServiceRegistryBuilder;
     9 
    10 public class HibernateUtil {
    11     public static final SessionFactory sessionFactory ;
    12     public static final ThreadLocal<Session> session = new ThreadLocal<Session>();
    13     static{
    14         try{
    15             //create the sessionFactory from hibernate.cfg.xml
    16             Configuration cf = new Configuration().configure();
    17             ServiceRegistry sr = new ServiceRegistryBuilder().applySettings(cf.getProperties()).buildServiceRegistry();  
    18             sessionFactory = cf.buildSessionFactory(sr);
    19         }catch(Throwable e){
    20             System.err.println("inital SessionFactory creation failed. " + e);
    21             throw new ExceptionInInitializerError(e);
    22         }
    23     }
    24     
    25     public static Session currrentSession()throws HibernateException{
    26         Session s = (Session)session.get();
    27         if(s == null){
    28             s = sessionFactory.openSession();
    29             session.set(s);
    30         }
    31         
    32         return s;
    33     }
    34     
    35     public static void closeSession()throws HibernateException{
    36         Session s = (Session)session.get();
    37         if(s != null){
    38             s.close();
    39             session.set(null);
    40         }
    41     }
    42 }
  • 相关阅读:
    jekins接通gitee的webhook做自动部署 vue、react、java、springBoot
    vue可复用性 & 组合
    vite使用短链接
    Ubuntu12.04(X86_64)上安装Mesa8.0.4
    回调函数
    c#隐式转换
    OpenGL ES2 的OffScreen实现
    Catch exception from other thread
    C# []、List、Array、ArrayList 区别及应用
    redhat update
  • 原文地址:https://www.cnblogs.com/binger/p/HibernateUtil.html
Copyright © 2011-2022 走看看