Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use only one SessionFactory Object per application?

Tags:

Why use only one SessionFactory Object per application? What are the advantages of using single session factory object per application?

like image 327
Viraj Dhamal Avatar asked Jan 19 '13 06:01

Viraj Dhamal


People also ask

Can we have multiple SessionFactory?

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.

How many objects of SessionFactory is required in a Hibernate application?

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.

Can SessionFactory be reused?

hibernate. HibernateException: HHH000469: The ClassLoaderService can not be reused.

How many instances of Session and SessionFactory are usually created?

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.


1 Answers

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.

like image 108
DarkHorse Avatar answered Sep 18 '22 14:09

DarkHorse