Java – hibernate session thread safety

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

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: is it safe to create a new entity in one thread and save it in another thread?

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 these entities are specially configured for urgent loading

Solution

>No The entity is attached to the session and contains the agent associated with the session (to delay itself) Doing so will use multi - threaded sessions Since the session is not thread safe, this is not a good idea. > Although the entity is temporary (i.e. newly created), it is not attached to the session. Hibernate does not understand it. The entity is a simple java object So no problem, I don't have all the details of your Dao If your Dao's method should be called as part of an existing transaction, it will not work properly because the transaction is related to the current thread

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>