为什么Hibernate阻止Java进程退出?

时间:2016-08-31 11:25:42

标签: java hibernate jpa

我该如何避免呢?

这是我的代码:

的persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
                                 http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
             version="2.1">
    <persistence-unit name="testdb" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <properties>
            <property name="hibernate.connection.driver_class" value="org.h2.Driver"/>
            <property name="hibernate.connection.url" value="jdbc:h2:tcp://localhost:9092/~/h2dbs/testdb"/>
            <property name="hibernate.connection.username" value="sa"/>
            <property name="hibernate.connection.password" value=""/>
            <property name="hibernate.connection.useUnicode" value="true"/>
            <property name="hibernate.connection.characterEncoding" value="utf-8"/>
            <property name="hibernate.show_sql" value="false"/>
        </properties>
    </persistence-unit>
</persistence>

PersistenceUtil.java

public class PersistenceUtil {

    private static EntityManagerFactory entityManagerFactory;

    static {
        entityManagerFactory = Persistence.createEntityManagerFactory("testdb");
    }

    public static EntityManager getEntityManager() {
        final EntityManager entityManager = entityManagerFactory.createEntityManager();
        return entityManager;
    }
}

和TestClass.java

public class TestClass {
    public static void main(String[] args) {
        final EntityManager em = PersistenceUtil.getEntityManager();
        final EntityTransaction transaction = em.getTransaction();
        transaction.begin();
        final TestTable testTable = new TestTable();
        testTable.setData("Sample Data");
        em.merge(testTable);
        transaction.commit();
        em.close();
    }
}

因此,当我在TestClass中运行main方法时,我会在DB中看到一行插入&#34; Sample Data&#34;很好,但程序永远不会退出,它只会挂起..

我认为Hibernate正在创建一个线程,但我该如何避免呢?

2 个答案:

答案 0 :(得分:2)

尝试关闭entityManagerFactory,在你的PersistenceUtil中只需要另外的方法来关闭entityManagerFactory

INPUT product_id department $10.;

答案 1 :(得分:1)

你可以尝试在名为close的PersistenceUtil上添加一个关闭EntityManagerFactory并查看主线程是否完成的方法