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?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With