Why only one sessionFactory object per database in Hibernate ?
Here we can explain what is SessionFactory..
• SessionFactory is an interface, which is available in “org.hibernate” package.
• Session factory is long live multithreaded object.
• Usually one session factory should be created for one database.
• When you have multiple databases in your application you should create multiple SessionFactory object.
• Assume the scenario that you are using one database called mysql in your application then following is the way to create the SessionFactory object :
Configuration cfg=new Configuration(); // Empty object will be created.
cfg=cfg.configure();
Here when you called configure() method It looks for hibernate-cfg.xml and for Hibernate mapping file filled with all the properties defined in the configuration documents and mapping documents.
SessionFactory sc=cfg.buildSessionFactory();
• SessionFactory object will be created once and will be used by multiple users for long time.
• Session Factory object is the factory for session objects.
If you are using two databases called mysql and oracle in your hibernate application then you need to
build 2 SessionFactory objects:
Configuration cfg=new Configuration();
Configuration cfg1=cfg.configure(“mysql.cfg.xml”);
SessionFactory sf1=cfg1.builed SessionFactory();
Configuration cfg2=cfg.configure(“oracle.cfg.xml”);
SessionFactory sf2=cfg2.builed SessionFactory();
When we are using more than one database in our application than we use the HibernateUtil class which is implemented based on singleton design pattern which insures that one and only one sessionFactory object will be created for entire application.Session factory objects are to be implemented using the singleton design pattern. Instances of SessionFactory are thread-safe and typically shared throughout an application. Because creation of a SessionFactory is an extremely expensive process which involves parsing hibernate configuration/mapping properties and creating database connection pool .Creating a database connection pool requires establishing database connections (i.e creating Connection objects) which has overhead due to the time taken to locate the DB server. So if you create a SessionFactory for every request , it implies that you are not using database connection pool to serve your request. So creating number of instances will make our application heavy weight. But the session objects are not thread safe. So in short it is - SessionFactory objects are one per application and Session objects are one per client.