hibernateUtils

来源:互联网 发布:sql server2008百度云 编辑:程序博客网 时间:2024/06/16 03:38

备忘:


Hibernate4.2.6 初始化sessionFactory,也可以使用单例模式。

public class HibernateUtil {private static SessionFactory sessionFactory = buildSessionFactory();private static SessionFactory buildSessionFactory(){ try {            // Create the SessionFactory from hibernate.cfg.xml        Configuration cfg = new Configuration().configure();        ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()                            .applySettings(cfg.getProperties())                            .buildServiceRegistry();        return cfg.buildSessionFactory(serviceRegistry);        }        catch (Throwable ex) {            // Make sure you log the exception, as it might be swallowed            System.err.println("Initial SessionFactory creation failed." + ex);            throw new ExceptionInInitializerError(ex);        }}public static SessionFactory getSessionFactory(){return sessionFactory;}}

获取session的两种方式比较:


1. openSession 从字面上可以看得出来,是打开一个新的session对象,而且每次使用都是打开一个新的session,假如连续使用多次,则获得的session不是同一个对象,并且使用完需要调用close方法关闭session。

  2. getCurrentSession ,从字面上可以看得出来,是获取当前上下文一个session对象,当第一次使用此方法时,会自动产生一个session对象,并且连续使用多次时,得到的session都是同一个对象,这就是与openSession的区别之一,简单而言,getCurrentSession 就是:如果有已经使用的,用旧的,如果没有,建新的。

 

注意 :在实际开发中,往往使用getCurrentSession多,因为一般是处理同一个事务(即是使用一个数据库的情况),所以在一般情况下比较少使用openSession或者说openSession是比较老旧的一套接口了;

 

对于getCurrentSession 来说,有以下一些特点:

1.用途,界定事务边界

2.事务提交会自动close,不需要像openSession一样自己调用close方法关闭session

3.上下文配置(即在hibernate.cfg.xml)中,需要配置:

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

(需要注意,这里的current_session_context_class属性有几个属性值:jta 、 thread 常用 , custom、managed 少用  )

a).thread使用connection 单数据库连接管理事务

b).jta (java  transaction api) Java 分布式事务管理 (多数据库访问),jta 由中间件提供(JBoss WebLogic 等, 但是tomcat 不支持)


0 0
原创粉丝点击