Hibernate中HibernateUtil

本文介绍了一个用于初始化Hibernate的工具类的设计方法,通过静态代码块实现SessionFactory的创建,并提供获取SessionFactory和Session的方法。此外,还详细解释了如何配置Hibernate及其配置文件的加载方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


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就类似与jdbcconnection.

 

 

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();
  }
 }

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值