Hibernate中HibernateUtil

Configuration cfg=new Configuration();
cfg.configure();
SessionFactory sf=cfg.buildSessionFactory();

这些代码希一般希望它只做一次,我们去做一个工具类去初始化hibernate。工具类一般不希望被继承,别人来改写自己的东西,一般用final。

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会在classpath中去找这个文件。src这个目录不是classpath,但是它可以找的到。因为src目录最终都会编译到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();
  }
 }

猜你喜欢

转载自blog.csdn.net/thomassamul/article/details/81476259