Hibernate's JNDI name binding is implemented in the net. sf. hibernate. impl. SessionFactoryObjectFactory program. Let's analyze the process of binding JNDI to Hibernate:
We get SessionFactory and write code like this:
Configuration conf = new Configuration (). addClass (Cat. class );
SessionFactory sf = conf. buildSessionFactory ();
The first step is to create a Configuration in new Configuration (), in which the Configuration file (hibernate. properties), and then save it to a Properties object. This property is related to JNDI:
Hibernate. session_factory_name hibernate/session_factory
Next, call the buildSessionFactory () method to check the configuration information, and then call a constructor of SessionFactoryImpl. Pay attention to the following two lines of code in the constructor:
Name = properties. getProperty (Environment. SESSION_FACTORY_NAME );
SessionFactoryObjectFactory. addInstance (uuid, name, this, properties );
The addInstance method of SessionFactoryObjectFactory is called and passed as a parameter. Finally, you can see the following code in the addInstance method:
Context ctx = NamingHelper. getInitialContext (properties );
NamingHelper. bind (ctx, name, instance );
Instance is the instance of SessionFactory. by reading the source code, we can clearly see that Hibernate is in conf. during buildSessionFactory (), the created SessionFactory instance is bound to the configuration file (hibernate. properties) in hibernate. session_factory_name indicates the name specified by the property. Therefore, Hibernate has dynamic binding of JNDI. However, Hibernate needs to obtain a SessionFactory instance for binding, and this SessionFactory instance requires us to write code for pre-creation, the process must be completed before all other programs that want to obtain the SessionFactory instance from JNDI.
Therefore, for any App Server, we do not have to worry about the binding process of the jndi name. We only need to ensure that a SessionFactory instance is created in advance, and Hibernate will do the rest of the work. So how can we ensure that the SessionFactory instance is pre-created? If it is a Servlet, you can configure an initial Servlet, as long as
Configuration conf = new Configuration (). addClass (Cat. class );
SessionFactory sf = conf. buildSessionFactory ();
This code can be added. For complex J2EE applications that contain ejbs, you may need to use the App Server function to pre-create a SessionFactory instance.