简体   繁体   中英

Handling Concurrent request with SpringBoot and Hibernate

I am creating a Web application using SpringBoot.In my application, I have RestController layer which will call Service Layer which in turn will call DAO layer. My Service layer is annotated with @Transactional(Spring transaction)

I have implemented DAO layer using Generic DAO Hibernate

    public class Dao{

        @Autowired(name = "sessionFactory")
        private SessionFactory sessionFactory;

        public <T> T save(final T o){
          return (T) sessionFactory.getCurrentSession().save(o);
        }


        public void delete(final Object object){
          sessionFactory.getCurrentSession().delete(object);
        }

        /***/
        public <T> T get(final Class<T> type, final Long id){
          return (T) sessionFactory.getCurrentSession().get(type, id);
        }

        /***/
        public <T> T merge(final T o)   {
          return (T) sessionFactory.getCurrentSession().merge(o);
        }

        /***/
        public <T> void saveOrUpdate(final T o){
          sessionFactory.getCurrentSession().saveOrUpdate(o);
        }
    }

In application.properties, I have spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext

So my concern is when multiple concurrent requests comes to my REST Controller Do I need to keep scope the service layer beans/DAO layer beans as prototype? Also, do I need to synchronize the methods in DAO layer? or getCurrentSession() will always return new session since hibernate session is not thread safe.

PS I do not want to use Spring Data JPA due to some specific reasons

So my concern is when multiple concurrent requests comes to my REST Controller Do I need to keep scope the service layer beans/DAO layer beans as prototype?

  • On the contrary, you need to keep bean as Singleton.

Also, do I need to synchronize the methods in DAO layer? or getCurrentSession() will always return new session since hibernate session is not thread safe.

You session as a Spring Bean, and by default is Singleton, so there will be only one instance for all requests.

Have you considered using spring-rest-data project?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM