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 }
  • 相关阅读:
    Intellij 常用技巧-持续更新
    Android界面组件的四种启动方式
    Preference Screen 首选项
    Oracle OCI-22053:溢出错误
    SQLPLUS使用
    Oracle中数字格式的文本化处理
    MP4V2 移植 (基于imx6 平台)
    IMX6Q camera 应用编程之 摄像头裁剪
    IMX6Q camera驱动分析 (4)
    IMX6Q Camera驱动分析 (3)
  • 原文地址:https://www.cnblogs.com/binger/p/HibernateUtil.html
Copyright © 2011-2022 走看看