EntityManager.close()未关闭与数据库Tomcat的连接

时间:2015-03-10 13:48:02

标签: java mysql tomcat jpa

这是我的JPA Utill Class ....

private static Logger logger=Logger.getLogger(JPAUtil.class);
private static EntityManager entityManager = null;
private static final ThreadLocal<EntityManager> threadLocal;

private static EntityManagerFactory emf = null;

static 
{
    try {

            emf = Persistence.createEntityManagerFactory("XYZ");
            threadLocal = new ThreadLocal<EntityManager>();

    } catch (Throwable ex) {
        logger.info("JPAUtil Exception",ex);
        throw new ExceptionInInitializerError(ex);
    }
}

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

        if (entityManager == null ||  !entityManager.isOpen()) {

            JPAUtil.entityManager = emf.createEntityManager();
            threadLocal.set(entityManager);

        }else if(!emf.isOpen())
        {
             entityManager = threadLocal.get();
            emf = Persistence.createEntityManagerFactory("XYZ");
            JPAUtil.entityManager = emf.createEntityManager();
            threadLocal.set(entityManager);
        }
    } catch (Throwable ex) {
        logger.info("JPAUtil Exception",ex);
        throw new ExceptionInInitializerError(ex);
    }
    return JPAUtil.entityManager;
}

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

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

public static void commit() {
    if (!entityManager.getTransaction().isActive()){
        entityManager.getTransaction().begin();
    }
entityManager.getTransaction().commit();
}
public static void rollback() {
    if (!entityManager.getTransaction().isActive()){
        entityManager.getTransaction().begin();
    }
    entityManager.getTransaction().rollback();
}

在每次交易之后,我正在关闭实体经理....

终于阻止......后来我开始知道即使在选择查询中我们也需要

开始交易并提交...所以我在我的应用程序主页

中尝试了

页面只是执行2个选择查询并且在服务器mysql中占用内存最多....使用eclipse MAT i Anallise Memory Leak ....

MAT Result

根据我的理解,因为我使用tomcat我不能连接池...我们将移动到jboss ...但直到我想要修补这个....任何帮助将不胜感激:): )

0 个答案:

没有答案