This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Originally posted by Sudhakar Reddy Kurakula: Configuration config=new Configuration.configure(); SessionFacotry session= config.buildSessionFactory(); Transaction trans=session.beginTransaction();
I want to Explanation for these lines.i.e what happens internally when the control comes to first statement and secondstatement like that.
First, a SessionFactory and a Session are two different things. a SessionFactory does not have a beginTransaction method.
So what Hibernate does is it reads the Hibernate Properties, most likely in your hibernate.cfg.xml, you could have a hibernate.properties but the cfg file is more recommended.
Anyway it reads the configuration, finds which mappings you have and it reads those mappings creating an object graph of everything you have mapped, creates or uses the Connection Pool, so that you can call openSession(), getCurrentSession(), or getStatelessSession() from the SessionFactory. The Session class has the beginTransaction() method. So opening a Session and beginning a Transaction is called a Unit of Work, it is when Hibernate can manage your objects, and also get access to the database.
A SessionFactory is heavy weight so you want only one instance of it, but opening sessions is lightweight and cheap.
Is SessionFactory is responsible for creating connection pool?
Can explain little bit about SessionFactory? or good reference material will do for me.
Thanks in advance.
Maybe, it can point to a DataSource in a container, so it won't create the pool there if you do that, but if you have Hibernate or a third part Connection Pool like C3PO, then yes, that will be part of what happens when a SessionFactory is created, it will start up the connection pool. The connection pool api does the rest.
The Configuration object reads the hibernate properties and the hibernate mappings files and creates the internal data structures about them. Usually your application will create just one Configuration, unless you're using multiple databases with different schemas.
The SessionFactory creates sessions. It also creates some things that are used collectively by the sessions it creates, such as a database connection pool and the second-level cache. Usually you will have one SessionFactory per Configuration. Exceptions might be if you have multiple databases using the same schema, or if you need to connect to the same database via different accounts (perhaps for security reasons).
Finally, a Session holds a database connection and its associated transaction and first-level cache.