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

标签 java database hibernate entitymanager

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/

相关文章:

java - 在 IntelliJ IDEA 中哪里可以找到已弃用方法的替代方法?

java - Java 中的线程和 ArrayList

android.database.sqlite.SQLiteDiskIOException : disk I/O error (code 1802)

python - 如何处理南方(django)的重构?

java - OneToOne Mapping 未设置映射对象

java - 将集合设置为 'new ArrayList()' 时级联 hibernate 删除

java - 下面的代码中有垃圾回收吗?

java - 如何从 VolleyError 获取响应代码?

java - 在文件系统中打开 Derby/JDBC 数据库

hibernate - hibernate : HQL Case Insensitive search