Hibernate会话线程安全 [英] Hibernate session thread safety

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

问题描述

我知道会话不是线程安全的。我的第一个问题是:将一个实体传递给另一个线程是安全的,对它做一些工作,然后将它传递回原始线程并更新。

  public class Example1 {
MyDao dao;
...
public void doWork(){
MyEntity entity = dao.getEntity();
Runnable job = new Job(entity);
线程t =新线程(工作);
t.run();
t.join();
dao.merge(entity);
}

}

第二个问题:它是否安全在一个线程中新建一个实体并保存到另一个线程中?

  public class Example2 {
MyDao dao;
...
public void doWork(){
MyEntity entity = new Entity();
new Thread(new Job(dao,entity))。run();
}
}

公共类Job实现了Runnable {
private MyDao dao;
私人MyEntity实体;
...
@Override
public void run(){
dao.save(entity);
}
}

编辑我忘了提及这些实体是专门配置用于加载的。

解决方案


  1. 实体附加到会话并包含链接到会话的代理(以便延迟加载自己)。这样做会使用来自多个线程的会话。由于会话不是线程安全的,所以这不是一个好主意。


  2. 虽然实体是暂时的(即,您刚用新建立了它) ,它没有附加到会话中,Hibernate不知道它,实体是一个普通的旧Java对象。所以没问题。我没有你的DAO的所有细节。如果您的DAO方法应该作为现有事务的一部分进行调用,那么这将不起作用,因为事务与当前线程绑定在一起。



I know that sessions are not thread safe. My first question: is it safe to pass an entity to another thread, do some work to it, then pass it back to the original thread and update.

public class Example1 {
    MyDao dao;
    ...
    public void doWork() {
        MyEntity entity = dao.getEntity();
        Runnable job = new Job(entity);
        Thread t = new Thread(job);
        t.run();
        t.join();
        dao.merge(entity);
    }

}

My second question: is it safe to new up an entity in one thread and save it in another?

public class Example2 {
    MyDao dao;
    ...
    public void doWork() {
        MyEntity entity = new Entity();
        new Thread(new Job(dao, entity)).run();
    }
}

public class Job implements Runnable {
    private MyDao dao;
    private MyEntity entity;
    ...
    @Override
    public void run() {
        dao.save(entity);
    }
}

Edit I forgot to mention that the entities are specifically configured for eager loading

解决方案

  1. No. The entity is attached to the session and contains proxies linked to the session (in order to lazy-load themselves). Doing that would thus use the session from multiple threads. Since the session is not thread-safe, this is not a good idea.

  2. While the entity is transient (i.e. you've just created it with new), it's not attached to the session, Hibernate doesn't know about it, and the entity is a plain old Java object. So no problem doing that.I don't have all the details of your DAO though. If the method of your DAO is supposed to be invoked as part of an existing transaction, that won't work, since the transaction is tied to the current thread.

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

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