在Hibernate中,多线程操作可以实现并发处理大量数据,提高系统吞吐能力。主要有以下两种实现方式:
1. SessionFactory级别线程安全:
- SessionFactory是线程安全的,可以被多个线程共享。每个线程调用openSession()开启自己的Session进行操作。
- 该方式简单易用,但Session不是线程安全的,同一个Session不能被多个线程共享。
例如:
SessionFactory factory = MetadataHelper.getSessionFactory();
new Thread() {
public void run() {
Session session = factory.openSession();
// 线程1的数据操作
}
}.start();
new Thread() {
public void run() {
Session session = factory.openSession();
// 线程2的数据操作
}
}.start();
2. CurrentSessionContext实现线程安全:
- 配置hibernate.current_session_context_class为org.hibernate.context.ThreadLocalSessionContext。
- 调用HibernateUtil的getCurrentSession()获取与当前线程绑定的Session,该Session是线程安全的,可以被同一线程的任意代码访问。
- 该方式灵活方便,可以同时实现Session的线程安全和重用。
例如:hibernate.cfg.xml配置
<property name="hibernate.current_session_context_class">
org.hibernate.context.ThreadLocalSessionContext
</property>
new Thread() {
public void run() {
Session session = HibernateUtil.getCurrentSession();
// 线程1的数据操作
}
}.start();
new Thread() {
public void run() {
Session session = HibernateUtil.getCurrentSession();
// 线程2的数据操作,可以访问session
}
}.start();