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?
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.
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.
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.
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()).
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