`
happyjeef18
  • 浏览: 15000 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

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分装完整版HQL查询

    标题"HibernateUtil分装完整版HQL查询"暗示了这是一个关于使用HibernateUtil工具类来封装和执行HQL(Hibernate Query Language)查询的教程或代码示例。描述中的重复信息进一步强调了这个主题,意味着我们将探讨如何...

    HibernateUtil 分页 增删改查 封装

    HibernateUtil 分页 增删改查 封装 HibernateUtil 分页 增删改查 封装 HibernateUtil 分页 增删改查 封装

    hibernate入门实例封装了HibernateUtil

    【标题】:Hibernate入门实例——基于HibernateUtil的数据库操作封装 在Java开发中,Hibernate作为一个强大的对象关系映射(ORM)框架,极大地简化了数据库操作。本实例将深入浅出地介绍如何使用Hibernate进行基本...

    06_传智播客hibernate教程_完善HibernateUtil类及hql查询入门

    本教程聚焦于“完善HibernateUtil类及HQL查询入门”,让我们深入探讨这两个关键概念。 首先,`HibernateUtil` 类是 Hibernate 教程中常见的一种工具类,它的主要作用是提供对 Hibernate 框架的简单封装,以方便进行...

    HibernateUtil工具类

    HibernateUtil工具类

    hibernate 一对多测试工程

    Session session = HibernateUtil.getSessionFactory().openSession(); Transaction transaction = session.beginTransaction(); Class class1 = new Class(); // set class1 properties List<Student> students =...

    HibernateUtil.java Hibernate5.2.1

    Hibernate5.2.1 的工具类 创建session 和 sessionFactory

    java util工具类

    HibernateUtil.java HibernateUtils.java HttpRequester.java HttpRespons.java HttpUtil.java MD5Util.java Pagination.java PropertiesUtil.java RegUtil.java StringUtil.java UploadUtil.java UUIDUtils.java

    Hibernate工具类

    `HibernateUtil`工具类就是对Hibernate框架功能的一种封装,简化了对数据库的操作。 在`HibernateUtil`工具类中,常见的方法有以下几类: 1. **初始化SessionFactory**: SessionFactory是Hibernate的核心组件,它...

    hibernateUtil.txt

    欢迎大家咨询,我会尽量去与大家讲解,希望对你们有所帮助

    对DAO编写单元测试源代码

    } <br> public String createPasswordTicket(User user) { HibernateUtil.executeUpdate( "delete from PasswordTicket as pt where pt.user=?", new Object[] { user } ); String ...

    基于泛型的通用Dao接口和hibernate的实现

    return HibernateUtil.getSession().createCriteria(clazz).list(); } @SuppressWarnings("unchecked") public List<T> findList(int pageNo, int pageSize) { return HibernateUtil.getSession()....

    hibernate学习笔记

    - **编写 HibernateUtil 工具类**:用于获取SessionFactory和Session,简化操作。 - **编写数据访问层**:使用HibernateUtil,实现CRUD(创建、读取、更新、删除)操作。 2. **Domain Object 规范** - **无参...

    hibernate 的各种操作

    Session session = HibernateUtil.currentSession(); // 获取当前会话 Transaction tx = null; // 事务 Users po = new Users(); // 实体对象 po = transCommerceInfoVOtoPO(vo, po); // 将 VO 转换为 PO try...

    案例课程B-S架构-1期 详细设计书9-公告管理模块.pdf

    - 模型层:在HibernateUtil中增加了公告新增的业务逻辑方法,接收封装用户输入的实体对象。 4. **公告删除** - 界面层:删除操作在公告列表页面中进行,无单独的删除界面。若用户无权限,会显示bbc_nomodify.jsp...

    六种方式实现hibernate查询

    s=HibernateUtil.getSession(); String hql="from Admin as admin where admin.aname=:name"; Query query=s.createQuery(hql); query.setString("name", name); List<Admin> list=query.list(); for(Admin ...

    案例课程B-S架构-1期 详细设计书18-审核批示模块.pdf

    控制层的`updateShen.jsp`逻辑页面接收用户输入,调用`HibernateUtil`中的`updateshenhe()`方法进行更新操作,并根据执行结果决定页面跳转。 3. **申请的审核**:未提供详细设计,通常涉及用户提交审批申请的功能。...

Global site tag (gtag.js) - Google Analytics