---
title: "Hibernate中HibernateUtil  "
author: "lkf009"
date: "2012-08-10T17:38:07Z"
tags: []
categories: ["编程语言"]
slug: "hibernate-hibernateutil"
draft: false
lastmod: "2012-08-10T17:39:00Z"
id: 1628514
url: "https://lkf009.iteye.com/blog/1628514"
---

Configuration cfg=new Configuration();  
cfg.configure();  
SessionFactory sf=cfg.buildSessionFactory();  
这些代码是非常耗时的，我们希望它只做一次，一般我们希望它只做一次，我们去做一个工具类去初始化hibernate。工具类一般不希望被继承，别人来改写我的东西,一般用finally.

 

package net.cnlib.util;

import org.hibernate.Session;  
import org.hibernate.SessionFactory;  
import org.hibernate.cfg.Configuration;

public final class HibernateUtil {  
 private static SessionFactory sessionFactory=null;  
 private HibernateUtil() {  
 }

 static {  
  Configuration cfg = new Configuration();  
  cfg.configure();  
  sessionFactory = cfg.buildSessionFactory();  
 }

 public static SessionFactory getSessionFactory() {  
  return sessionFactory;  
 }

 public static Session getSession(){  
  return  sessionFactory.openSession();  
 }  
   
}

 cfg.configure()这句话就会去读hibernate.cfg.xml里面的配置文件.如果你的配置文件不叫hibernate,cfg.xml,你就要用cfg.configure("filename")来指定你需要的配置文件。我们可以查看源代码。在使用cfg.configure()时：

 public Configuration configure() throws HibernateException {  
  configure( "/hibernate.cfg.xml" );  
  return this;  
 }

会把hibernate.cfg.xml传进去,eclipse会在哪里去找这个hibernate.cfg.xml这个文件呢？会在classpath中去找这个文件。src这个目录不是classpath，但是它为什么可以找的到呢？因为scr目录最终都会编译到classpath中去。session就类似与jdbc的connection.

 

 

Hibernate 中先对来说比较规范的一个添加一个对象的写法

 static void addPerson(Person person) {  
  Session session = null;  
  Transaction tx = null;  
  try {  
   session = HibernateUtil.getSession();  
   tx = session.beginTransaction();  
   session.save(person);

  } catch (HibernateException e) {  
   if (tx != null)  
    tx.rollback();  
   throw e;  //这个时候最好是把异常抛出去，因为如果只是回滚的话，就没有任何提示给调用者。  
  } finally {  
   session.close();  
  }  
 }