eclipse hibernate自动生成需要注意的几点

一、sessionFactory的创建

eclipse hibernate 自动生成后,dao类中的sessionFactory的创建

protected SessionFactory getSessionFactoy() { 
return (SessionFactory) new InitialContext().lookup("SessionFactory");
}

    会提示Could not locate SessionFactory in JNDIjavax.naming.NoInitialContextException,应该改为:
return new Configuration().configure().buildSessionFactory();
    这样做法也有不妥,因为对于SessionFactory实例是线程安全的(Session实例不是线程安全的),所以每个操作都可以共用同一个SessionFactory来获取Session。一般情况下一个应用中一个数据库共享一个SessionFactory实例。

    所以应该把构建SessionFactory要放在静态代码块中,因为它只在该类被加载时执行一次。正确做法如下

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

public class HibernateUtil {
	private static SessionFactory sessionFactory;

	  static {
	    try {
	       sessionFactory = new Configuration().configure().buildSessionFactory();
	    } catch (Throwable ex) {
	       throw new ExceptionInInitializerError(ex);
	    }
	  }

	  public static SessionFactory getSessionFactory() {
	      // Alternatively, we could look up in JNDI here
	      return sessionFactory;
	  }

	  public static void shutdown() {
	      // Close caches and connection pools
	      getSessionFactory().close();
	  }

}

二、session的获取

eclipse hibernate 自动生成后,session的获取是通过

sessionFactory.getCurrentSession()
来获取的,与openSession方法有所不同

1、getCurrentSession()与openSession()的区别?
    * 采用getCurrentSession()创建的session会绑定到当前线程中,而采用openSession()
    创建的session则不会
    * 采用getCurrentSession()创建的session在commit或rollback时会自动关闭,而采用openSession()
    创建的session必须手动关闭

    sessionFactory.getCurrentSession()方法取得的session,在做数据库操作时必须在事务中做,包括只读的查询,否则会报错。

2、使用getCurrentSession()需要在hibernate.cfg.xml文件中加入如下配置:
    * 如果使用的是本地事务(jdbc事务)

    <property name="hibernate.current_session_context_class">thread</property>

    * 如果使用的是全局事务(jta事务)

     <property name="hibernate.current_session_context_class">jta</property>

    在 SessionFactory 启动的时候, Hibernate 会根据配置创建相应的 CurrentSessionContext ,在 getCurrentSession() 被调用的时候,实际被执行的方法是 CurrentSessionContext.currentSession() 。在 currentSession() 执行时,如果当前 Session 为空, currentSession 会调用 SessionFactory 的 openSession 。所以 getCurrentSession() 对于 Java EE 来说是更好的获取 Session 的方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值