The hibernate Jndi name bindings are implemented in the Net.sf.hibernate.impl.SessionFactoryObjectFactory program, and I'll analyze the process of hibernate binding Jndi:
The way we get sessionfactory is generally to write code like this:
Configuration conf = new Configuration().addClass(Cat.class);
SessionFactory sf = conf.buildSessionFactory();
First, the new Configuration () creates a Configuration that reads the configuration file (hibernate.properties) inside the constructor and then saves it to a properties object. This attribute is associated with Jndi:
hibernate.session_factory_name hibernate/session_factory
Then call the Buildsessionfactory () method, which examines the configuration information and then calls a constructor for Sessionfactoryimpl. Notice the following two lines of code inside the builder:
name = properties.getProperty(Environment.SESSION_FACTORY_NAME);
SessionFactoryObjectFactory.addInstance(uuid, name, this, properties);
The Sessionfactoryobjectfactory Addinstance method is invoked and its own (sessionfactory instance) is passed as a parameter. Finally, the following code can be seen in the Addinstance method:
Context ctx = NamingHelper.getInitialContext(properties);
NamingHelper.bind(ctx, name, instance);
Instance is a sessionfactory example, by reading the source code, you can clearly see that hibernate is in Conf.buildsessionfactory () through a series of class method calls, Bind the created Sessionfactory instance to the name specified by the Hibernate.session_factory_name property in the configuration file (hibernate.properties). Therefore, the visible hibernate itself is a dynamic binding function with Jndi. But hibernate needs to get a sessionfactory instance for binding, and this sessionfactory instance requires us to write code to create it beforehand, You must also ensure that the process is completed before all other programs to get the Sessionfactory instance from Jndi.
So for any app server, we don't have to go through the process of binding the Jndi name, just make sure it's enough to create a sessionfactory instance beforehand, and the rest of the work hibernate. So how do you make sure that you create a sessionfactory instance, and if it's a servlet, you can configure an initialized servlet, just
Configuration conf = new Configuration().addClass(Cat.class);
SessionFactory sf = conf.buildSessionFactory();
This kind of code can be added in. If you are a complex Java application that contains EJBS, you may need to rely on the functionality of the app server to ensure that you create sessionfactory instances.