gpt4 book ai didi

java - 多线程应用程序中的EntityManager?

转载 作者:行者123 更新时间:2023-12-01 23:17:33 26 4
gpt4 key购买 nike

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

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

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

或者我是否必须为每个线程以及每个关闭 EM 的事务重新创建实体管理器?

我的 CRUD 方法将如下所示:

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 实例?

最佳答案

<强> 5.1. Entity manager and transaction scopes :

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 处理多个事务,只要这些事务是工作单元的一部分。

此外,在 closed 之后,您将无法使用 EntityManger它:

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();
}

}

关于java - 多线程应用程序中的EntityManager?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20997410/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com