A SessionFactory is pretty heavyweight, so, we recommend creating one and caching it in a singleton type of way. Then, you can create as many Session objects from it as you like.
http://www.hiberbook.com/HiberBookWeb/l ... hhibernateQuote:
The SessionFactory and Resource Allocation
The SessionFactory itself is a fairly resource intensive object to create. In the first few Hibernate tutorials on this website, we'll typically create SessionFactory objects whenever we need them, but in practice, it is imperative to control how often the SessionFactory gets created. Minimizing the number of SessionFactory objects you create can be done by perhaps making the SessionFactory a static variable that is accessed through a Singleton design pattern, or better yet, in a J2EE environment, simply have the SessionFactory bound to, and accessed through, the JNDI naming service of the J2EE application server. You really only need one SessionFactory in any application. Controlling the number of SessionFactory objects that get created, and for that matter, destroyed, will help to minimize unnecessary resource allocations.
On the other hand, the Hibernate Session, which is produced by the SessionFactory, is a very efficient object that you don't have to feel guilty about creating willy-nilly. A single SessionFactory is great at efficiently pumping out Hibernate Session objects whenever you need them. Limit the number of SessionFactory objects that are created in an enterprise application to one, but feel guilt-free about generating Hibernate Sessions whenever you need them.
Sessions and the org.hibernate.SessionFactory
It doesn't take a genius to figure out that the job of the SessionFactory is to pump out Hibernate Session objects. Obtaining the Session is actually a pretty straight forward endeavor once you have access to the SessionFactory, as you simply have to invoke the factory's getCurrentSession() method.
Code:
AnnotationConfiguration config =
new AnnotationConfiguration();
config.addAnnotatedClass(User.class);
config.configure();
// new SchemaExport(config).create(true, true);
SessionFactory factory = config.buildSessionFactory();
Session session = factory.getCurrentSession();
/* a session is around, but
the User is still transient! */
User u = new User(); u.setPassword("abc123");
http://www.hiberbook.com/HiberBookWeb/l ... hhibernate