Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create session factory in Hibernate 4

Tags:

java

hibernate

I'm having trouble generating a session factory in Hibernate 4. In Hibernate 3 I simple did:

org.hibernate.cfg.Configuration conf= HibernateUtil     .getLimsInitializedConfiguration(systemConfiguration .getHibernateconfFile());  SessionFactory sf = conf.configure().buildSessionFactory(); 

Now I need to pass a ServiceRegistry class to buildSessionFactory, but the Javadocs are extremely vague on how to go about this. Any tips?

like image 781
MTR Avatar asked Nov 02 '11 20:11

MTR


People also ask

What is session factory in Hibernate?

The SessionFactory is a thread safe object and used by all the threads of an application. The SessionFactory is a heavyweight object; it is usually created during application start up and kept for later use. You would need one SessionFactory object per database using a separate configuration file.

Can we create multiple session factory in Hibernate?

Q. What we can create more than one sessionFactory in Hibernate. Ans And Its true We can create.As in my app i am able to da same.

How can I open session factory in Hibernate?

Hibernate SessionFactory openSession() method always opens a new session. We should close this session object once we are done with all the database operations. We should open a new session for each request in multi-threaded environment.


1 Answers

Yes, they have deprecated the previous buildSessionFactory API, and it's quite easy to do well.. you can do something like this..

EDIT : ServiceRegistryBuilder is deprecated. you must use StandardServiceRegistryBuilder

public void testConnection() throws Exception {              logger.info("Trying to create a test connection with the database.");             Configuration configuration = new Configuration();             configuration.configure("hibernate_sp.cfg.xml");             StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());             SessionFactory sessionFactory = configuration.buildSessionFactory(ssrb.build());             Session session = sessionFactory.openSession();             logger.info("Test connection with the database created successfuly.");     } 

For more reference and in depth detail, you can check the hibernate's official test case at https://github.com/hibernate/hibernate-orm/blob/master/hibernate-testing/src/main/java/org/hibernate/testing/junit4/BaseCoreFunctionalTestCase.java function (buildSessionFactory()).

like image 85
Love Hasija Avatar answered Sep 30 '22 13:09

Love Hasija