跨多线程的Spring + Hibernate会话管理 [英] Spring + Hibernate session management across multiple threads

查看:129
本文介绍了跨多线程的Spring + Hibernate会话管理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个系统,其中来自客户端的每个请求在服务器端产生多个线程。然后每个线程正在使用一个或多个DAO(某些DAO可以在当时被多个线程使用)。所有的DAO都被Spring注入到我的线程类中( @Autowired )。每个DAO还接收 SessionFactory

在这些多个DAO中管理Hibernate会话的正确方法是什么,所以我不会因为多线程环境而遇到问题(例如,来自不同线程的少量DAO试图使用同一个会话)?



在Hibernate配置中指定 hibernate.current_session_context_class = thread 就足够了,然后每次在DAO中使用 SessionFactory.getCurrentSession()来完成这项工作?它会根据需要正确检测和创建每个线程的会话吗?

是的。这是足够的。



设置 hibernate.current_session_context_class 线程,从 SessionFactory.getCurrentSession()返回的会话来自 ThreadLocal 实例。



每个线程都有自己的,独立的 ThreadLocal 实例,所以不同的线程不会访问同一个hibernate会话。



SessionFactory.getCurrentSession()的行为是:如果在当前线程中第一次调用它,打开并返回。如果它在同一个线程中被再次调用,则会返回相同的会话。因此,只需调用 SessionFactory.getCurrentSession(),就可以在同一事务代码中的不同DAO方法中使用相同的会话。 。如果您必须在同一事务代码中调用多个不同的DAO方法,它会阻止您通过DAO方法的输入参数传递Hibernate会话。


I am building a system, where each request from a client side spawns multiple threads on server side. Each thread then is using one or more DAOs (some DAOs can be used by more than one thread at the time). All DAOs are injected (@Autowired) to my thread classes by Spring. Each DAO receives SessionFactory injected as well.

What would be proper way of managing Hibernate sessions across these multiple DAOs so I would not run into problems because of multithreaded environment (e.g. few DAOs from different threads are trying to use the same session at the same time)?

Would be enough that I specify hibernate.current_session_context_class=thread in Hibernate configuration and then everytime in DAO simply use SessionFactory.getCurrentSession() to do the work? Would it properly detect and create sessions per thread as needed?

解决方案

Yes. It is enough.

When setting hibernate.current_session_context_class to thread , the session returned from SessionFactory.getCurrentSession() is from the ThreadLocal instance .

Every thread will have their own, independently ThreadLocal instance , so different threads will not access to the same hibernate session .

The behaviour of SessionFactory.getCurrentSession() is that : if it is called for the first time in the current thread, a new Session is opened and returned . If it is called again in the same thread , the same session will be returned.

As a result , you can get the same session to use in different DAO methods in the same transaction code by simply calling SessionFactory.getCurrentSession() . It prevent you from passing the Hibernate session through the DAO method 's input parameters in the case that you have to call many different DAO methods in the same transaction code .

这篇关于跨多线程的Spring + Hibernate会话管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆