Reputation: 299
They say that to build a session factory in NHibernate is expensive and that it should only happen once. I use a singleton approach on this. This is done on the first time that a session is requested.
My question : Would there every be a time when you should close the Session factory? If so, when would one do this?
Upvotes: 4
Views: 6080
Reputation: 2096
To AZ: This is referring to the SessionFactory, not the session. Though I wouldn't say there should only be one instance of SessionFactory. There should be one per unique configuration. For instance, if a single app is connecting to 2 different databases, then you need 2 different SessionFactory instances.
Upvotes: 2
Reputation: 6779
There should be only one instance of sessionfactory . The code above is not an example of singleton pattern. If you are working in an enterprise application, I would suggest use Spring with hibernate . That would help you out in managing transactions and take away all this headache of managing session factory
Upvotes: 0
Reputation: 831
This is what i do in Java with Hibernate :
public class HibernateUtil
{
private static final SessionFactory sessionFactory;
static
{
try
{
// Create the SessionFactory from hibernate.cfg.xml
sessionFactory = new Configuration().configure().buildSessionFactory();
}
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;
}
}
You can free your SessionFactory when you don't need it anymore I guess, but honestly I've never closed my session factory
Upvotes: 6