Home > Database > Mysql Tutorial > body text

Hibernate的JNDI绑定分析_MySQL

WBOY
Release: 2016-06-01 14:07:09
Original
1057 people have browsed it

HibernateJNDI

  Hibernate的JNDI名称绑定是在net.sf.hibernate.impl.SessionFactoryObjectFactory程序里面实现的,我来分析一下Hibernate的绑定JNDI的过程:

  我们获得SessionFactory一般是这样写代码:

  Configuration conf = new Configuration().addClass(Cat.class);
  SessionFactory sf = conf.buildSessionFactory();

  首先是new Configuration()创建一个Configuration,在这个构造器里面进行配置文件(hibernate.properties)的读取工作,然后保存到一个Properties对象里面去,和JNDI相关的是这个属性:

  hibernate.session_factory_name hibernate/session_factory

  接着调用buildSessionFactory()方法,该方法检查一下配置信息,然后调用SessionFactoryImpl的一个构造器。在构造器里面注意下面两行代码:

  name = properties.getProperty(Environment.SESSION_FACTORY_NAME);
  SessionFactoryObjectFactory.addInstance(uuid, name, this, properties);

  调用了SessionFactoryObjectFactory的addInstance方法,并且把自身(SessionFactory的实例)作为参数传递。最后在addInstance方法可以看到如下代码:

  Context ctx = NamingHelper.getInitialContext(properties);
  NamingHelper.bind(ctx, name, instance);

  instance 就是SessionFactory的实例,通过读源代码,可以清楚的看到Hibernate是在conf.buildSessionFactory()的时候通过一系列类方法调用,把创建的SessionFactory实例绑定到配置文件(hibernate.properties)中 hibernate.session_factory_name属性指定的名称上的,因此可见Hibernate自身是具有JNDI的动态绑定功能的。但是Hibernate需要获得一个SessionFactory实例用于绑定,而这个SessionFactory实例需要我们写代码进行预先创建,并且必须保证该过程要在所有其它要从JNDI上获得SessionFactory实例的程序之前完成。

  因此对于任何App Server来说,我们都不必去管JNDI名称的绑定过程,只需要保证预先创建一个SessionFactory实例出来就够了,剩下的工作 Hibernate会做的。那么如何确保预创建SessionFactory实例呢,如果是Servlet,可以配置一个初始化的Servlet,只要把

  Configuration conf = new Configuration().addClass(Cat.class);
  SessionFactory sf = conf.buildSessionFactory();

  这样的代码加进去就可以了。如果是包含EJB的的复杂的J2EE应用,可能需要依靠App Server的功能来保证预创建SessionFactory实例。



Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!