我有一个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();
我的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>
什么可能导致测试永远不会完成?
答案 0 :(得分:0)
我发现我必须关闭EntityManagerFactory才能完成测试。而不是
entMgr.close();
我应该写
entMgr.getEntityManagerFactory.close();
通过这条新线,测试结束,每个人都很高兴:)