0

Following is my Bean configuration

@Bean
        public SessionFactory getSessionFactoryBean(@Autowired(required = true) HikariDataSource dataSource) {

        LocalSessionFactoryBean sessionFacBean = new LocalSessionFactoryBean();
        sessionFacBean.setDataSource(dataSource);
        sessionFacBean.setPackagesToScan("com.project");
        Properties hibernateProperties = new Properties();
        hibernateProperties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
        sessionFacBean.setHibernateProperties(hibernateProperties);
        try {
            sessionFacBean.afterPropertiesSet();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return sessionFacBean.getObject();

    }

I use this 'SessionFactory' Bean in my controller class. As far as I know, spring creates a new thread with new instance of a controller class during multiple requests. In that case, a new instance of 'SessionFactory' bean will also be autowired to the controller (Explained in this link). The whole point of this sessionFactory is ConnectionPooling, If the sessionFactory is created for each request then How does the connection pooling works properly.

I have the similar situation for other beans too, HttpClient and MongoTemplate with connection pooling.

Please feel free to edit the question if my understanding is wrong.I'm a newbie to all this.

1 Answers1

0
  1. You should have only one SessionFactory for your application. It should be configured during application startup.
  2. Each thread should have their own Session. There are various approaches how to use a Session with requests: https://stackoverflow.com/a/37526397/3405171

In that case, a new instance of 'SessionFactory' bean will also be autowired to the controller

This is incorrect. @Bean annotation has singleton scope as default. So you will have only one SessionFactory for all threads and controllers.

The whole point of this sessionFactory is ConnectionPooling

To speak more correctly a DataSource is responsible for a connection pool. SessionFactory is for Hibernate specific stuff like persistent classes metadata, SQL generating etc.

Also keep in mind that Hibernate has org.hibernate.context.spi.CurrentSessionContext which controls how the Session is bounded to the thread.

v.ladynev
  • 16,591
  • 5
  • 37
  • 56