JAVA:多线程环境中的EntityManager对象 [英] JAVA: an EntityManager object in a multithread environment

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

问题描述

如果我有多个线程,每个使用注入器来获取EntityManager对象,每个使用em对象来选择其他类对象的列表。准备在for循环中使用。

if I have multiple threads, each use injector to get the EntityManager object, each use the em object to select a list of other class objects. Ready to be used in a for loop.

如果线程先完成并调用clear(),那会影响其他线程吗?就像for循环会有例外吗?

If a thread finishes first and calls clear(), will that affect the other threads? Like the for loop will have exception?

close()怎么样?

How about close()?

如果答案是它依赖于什么(类定义?方法调用?)和where(java code?annotation?xml?)我应该查看它是如何依赖的?

If the answer is "It depends", what (class definition? method call?) and where (java code? annotation? xml?) should I look at to find out how is it depended?

我没有写源,我只是在没有文档的情况下使用别人的库。

I did not write the source, I am just using someone else's library without documentation.

谢谢。

推荐答案

这是完整的工作线程安全的实体经理助手

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class EntityManagerHelper {

    private static final EntityManagerFactory emf;
    private static final ThreadLocal<EntityManager> threadLocal;

    static {
        emf = Persistence.createEntityManagerFactory("Persistent_Name");
        threadLocal = new ThreadLocal<EntityManager>();
    }

    public static EntityManager getEntityManager() {
        EntityManager em = threadLocal.get();

        if (em == null) {
            em = emf.createEntityManager();
            // set your flush mode here
            threadLocal.set(em);
        }
        return em;
    }

    public static void closeEntityManager() {
        EntityManager em = threadLocal.get();
        if (em != null) {
            em.close();
            threadLocal.set(null);
        }
    }

    public static void closeEntityManagerFactory() {
        emf.close();
    }

    public static void beginTransaction() {
        getEntityManager().getTransaction().begin();
    }

    public static void rollback() {
        getEntityManager().getTransaction().rollback();
    }

    public static void commit() {
        getEntityManager().getTransaction().commit();
    }
}

这篇关于JAVA:多线程环境中的EntityManager对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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