Java 休眠测试未完成

Java 休眠测试未完成,java,mysql,hibernate,jpa,Java,Mysql,Hibernate,Jpa,我有一个Java应用程序,通过Hibernate连接到MySQL数据库 我已经编写了一个测试来测试与数据库的连接,但它永远不会结束。两个线程正在运行,但我在测试中编写的所有代码都已执行。这两条线是: Thread [pool-1-thread-1] (Running) Thread [DestroyJavaVM] (Running) 以下是我的测试文件: Vote v1 = new Vote(0, "abc"); Vote v2 = new Vote(1, "def"); Cand

我有一个Java应用程序,通过Hibernate连接到MySQL数据库

我已经编写了一个测试来测试与数据库的连接,但它永远不会结束。两个线程正在运行,但我在测试中编写的所有代码都已执行。这两条线是:

Thread [pool-1-thread-1] (Running)  
Thread [DestroyJavaVM] (Running)    
以下是我的测试文件:

Vote v1 = new Vote(0, "abc");
Vote v2 = new Vote(1, "def");
Candidate c1 = new Candidate(0, "First Candidate");
Timestamp t = new Timestamp(0, 123456l);

EntityManager entMgr = EntityManagerUtil.getEntityManagerFactory().createEntityManager();
EntityTransaction transaction = entMgr.getTransaction();
transaction.begin();

VoteRepository vr = new VoteRepository(entMgr);
entMgr.persist(v1);
entMgr.persist(v2);

CandidateRepository cr = new CandidateRepository(entMgr);
entMgr.persist(c1);

TimestampRepository tr = new TimestampRepository(entMgr);
entMgr.persist(t);

transaction.commit();
entMgr.close();
My persistence.xml如下所示:

<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
    <!-- This is where we tell JPA/Hibernate about our @Entity objects -->
    <class>org.evoting.database.entities.Candidate</class>
    <class>org.evoting.database.entities.Timestamp</class>
    <class>org.evoting.database.entities.Vote</class>

<properties>
    <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
    <property name="javax.persistence.jdbc.url" value="jdbc:mysql://url" />
    <property name="javax.persistence.jdbc.user" value="***" />
    <property name="javax.persistence.jdbc.password" value="***" />
    <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />

    <!-- Update the database schema on startup: "update"; "validate" to only check -->
    <property name="hibernate.hbm2ddl.auto" value="update" />

    <!-- Echo all executed SQL to stdout -->
    <property name="hibernate.show_sql" value="true" />

    <!-- Disable the second-level cache -->
    <property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvicer" />

    <property name="hibernate.format_sql" value="true" />
    <property name="hibernate.transaction.flush_before_completion" value="true" />
    <property name="hibernate.connection.autocommit" value="false" />
    <property name="hibernate.connection.release_mode" value="after_transaction" />
</properties>

什么会导致测试永远无法完成?

我发现我必须关闭EntityManager工厂才能完成测试。所以不是

entMgr.close();
我应该写

entMgr.getEntityManagerFactory.close();

有了这一行,测试结束了,每个人都很高兴:

发布测试方法和类的完整代码。您是否将测试声明为具有回滚的事务性测试。看它是完整的代码。这只是一个简单的旧main方法;在整个方法中,您可以准确地找出哪一行正在停止执行。最后一行已执行,但两个线程仍在运行。