在多线程应用程序中的EntityManager? [英] EntityManager in multithread app?

查看:319
本文介绍了在多线程应用程序中的EntityManager?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在多线程应用程序中如何使用Hibernate EntityManager (例如,每个客户端连接在服务器上启动它自己的线程)。

How is a Hibernate EntityManager to be used in a multi thread application (eg each client connection starts it's own thread on the server).

应仅由EntityManagerFactory创建一次EntityManager,例如:

Should EntityManager only created once by EntityManagerFactory, like:

private static EntityManagerFactory emf = Persistence.createEntityManagerFactory("unit");
private static EntityManager em = emf.createEntityManager();
    public static EntityManager get() {
        return em;
    }

还是我必须为每个线程和每个事务重新创建实体?

Or do I have to recreate the entitymanger for every thread, and for every transaction that closes the EM?

我的CRUD方法如下所示:

My CRUD methods will look like this:

public void save(T entity) {
    em.getTransaction().begin();
    em.persist(entity);
    em.getTransaction().commit();
    em.close();
}

public void delete(T entity) {
    em.getTransaction().begin();
    em.remove(entity);
    em.getTransaction().commit();
    em.close();
}

我是否必须运行 emf.createEntityManager() 在每个 .begin()之前?还是因为每个人都在使用自己的缓存创建自己的EntityManager实例而使我陷入麻烦?

Would I havew to run emf.createEntityManager() before each .begin()? Or am I then getting into trouble because each is creating an own EntityManager instance with it's own cache?

推荐答案

5.1。实体管理器和事务作用域

5.1. Entity manager and transaction scopes:


EntityManager是一种便宜的,非线程安全的对象,应使用一次,对于
单个业务流程,是单个工作单元,然后丢弃。

An EntityManager is an inexpensive, non-threadsafe object that should be used once, for a single business process, a single unit of work, and then discarded.

这完全可以回答您的问题。不要通过线程共享EM。只要这些交易是工作单元的一部分,就可以使用一个EM。

This answers perfectly your question. Don't share EMs over threads. Use one EM for several transactions as long as those transactions are part of a unit of work.

此外,之后您不能使用EntityManger您已经关闭了:

Furthermore you can't use an EntityManger after you've closed it:


在调用close方法之后,EntityManager实例上的所有方法以及从中获取的任何Query,TypedQuery和StoredProcedureQuery对象都将抛出IllegalStateException。

After the close method has been invoked, all methods on the EntityManager instance and any Query, TypedQuery, and StoredProcedureQuery objects obtained from it will throw the IllegalStateException.

请考虑以下内容:

public class Controller {

    private EntityManagerFactory emf;

    public void doSomeUnitOfWork(int id) {
        EntityManager em = emf.createEntityManager();
        em.getTransaction().begin();

        CrudDao dao = new CrudDao(em);

        Entity entity = dao.get(id);
        entity.setName("James");
        dao.save(entity);

        em.getTransaction.commit();
        em.close();
    }

}

这篇关于在多线程应用程序中的EntityManager?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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