Why use only one SessionFactory Object per application? What are the advantages of using single session factory object per application?
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.
You would need one SessionFactory object per database using a separate configuration file. So, if you are using multiple databases, then you would have to create multiple SessionFactory objects.
hibernate. HibernateException: HHH000469: The ClassLoaderService can not be reused.
Sessionfactory will create and manage the sessions. If you have say, 4 datasources/databases, then you must create 4 session factory instances. sessionfactory is an immutable object and it will be created as a singleton while the server initializes itself.
Session factory objects are to be implemented using the singleton design pattern. Instances of SessionFactory are thread-safe and typically shared throughout an application. As these objects are heavy weight because they contains the connection information, hibernate configuration information and mapping files,location path. 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.
Hence it would be one SessionFactory per DataSource. Your application may have more than one DataSource so you may have more than one SessionFactory in that instance. But you would not want to create a SessionFactory more than once in an application.
Advantages: Obviously its improving performance of your application :)
UPDATE - Extract from Hibernate Doc
The internal state of a SessionFactory is immutable. Once it is created this internal state is set. This internal state includes all of the metadata about Object/Relational Mapping.
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