关闭

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

标签: 工具nullclass
478人阅读 评论(0) 收藏 举报
分类:
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);
    }
}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:100700次
    • 积分:1663
    • 等级:
    • 排名:千里之外
    • 原创:64篇
    • 转载:27篇
    • 译文:0篇
    • 评论:11条
    文章分类
    最新评论