Java 使用SpringBoot和Hibernate处理并发请求

Java 使用SpringBoot和Hibernate处理并发请求,java,spring,hibernate,spring-boot,Java,Spring,Hibernate,Spring Boot,我正在使用SpringBoot创建一个Web应用程序。在我的应用程序中,我有一个RestController层,它将调用服务层,而服务层又将调用DAO层。 我的服务层用@Transactional(Spring事务)注释 我已经使用通用DAO Hibernate实现了DAO层 public class Dao{ @Autowired(name = "sessionFactory") private SessionFactory sessionFactor

我正在使用SpringBoot创建一个Web应用程序。在我的应用程序中,我有一个RestController层,它将调用服务层,而服务层又将调用DAO层。 我的服务层用@Transactional(Spring事务)注释

我已经使用通用DAO Hibernate实现了DAO层

    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);
        }
    }
公共类Dao{
@自动连线(name=“sessionFactory”)
私人会话工厂会话工厂;
公共T保存(最终T o){
返回(T)sessionFactory.getCurrentSession().save(o);
}
公共无效删除(最终对象){
sessionFactory.getCurrentSession().delete(对象);
}
/***/
公共T get(最终类类型,最终长id){
return(T)sessionFactory.getCurrentSession().get(类型,id);
}
/***/
公共T合并(最终T o){
return(T)sessionFactory.getCurrentSession().merge(o);
}
/***/
公共作废保存或更新(最终版本){
sessionFactory.getCurrentSession().saveOrUpdate(o);
}
}
在application.properties中,我有 spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext

所以我关心的是当多个并发请求到达我的REST控制器时 我是否需要将服务层bean/DAO层bean作为原型? 另外,我是否需要同步DAO层中的方法?或者getCurrentSession()将始终返回新会话,因为hibernate会话不是线程安全的

由于某些特定的原因,我不想使用SpringDataJPA

所以我关心的是当多个并发请求进入我的REST时 控制器我需要保留服务层bean/DAO层的作用域吗 豆子作为原型

  • 相反,您需要将bean保持为Singleton
另外,我是否需要同步DAO层中的方法?或 getCurrentSession()将在休眠后始终返回新会话 会话不是线程安全的

您可以将会话作为Springbean,默认情况下是Singleton,因此所有请求只有一个实例


您是否考虑过使用spring rest数据项目?

鉴于上述配置,getcurrentsession方法是否将始终返回新的会话对象,因为spring boot中的嵌入式tomcat将为每个请求创建新线程?请实现,检查是否相等,并查看它是否真的是新对象。