使用LocalThread来管理实体的工具类
package common;

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

public abstract class EntityManagerTool {

    private static final ThreadLocal<EntityManager> threadLocal = new ThreadLocal<EntityManager>();

    private static EntityManagerFactory entityManagerFactory = null;

    static {
	if (entityManagerFactory == null)
	    entityManagerFactory = Persistence .createEntityManagerFactory("forTest");
    }

    public static EntityManager getEntityManager() {
	EntityManager em = threadLocal.get();
	if (em == null) {
	    em = entityManagerFactory.createEntityManager();
	    threadLocal.set(em);
	}
	return em;
    }

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

阅读更多
文章标签: 工具 null class
个人分类: 知识
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

使用LocalThread来管理实体的工具类

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭