【发布时间】:2019-02-28 01:29:30
【问题描述】:
我有一些简短的单元测试失败,但有例外:
javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: could not prepare statement
::
Caused by: org.hibernate.exception.GenericJDBCException: could not prepare statement
::
Caused by: org.h2.jdbc.JdbcSQLException: Database is already closed (to disable automatic closing at VM shutdown, add ";DB_CLOSE_ON_EXIT=FALSE" to the db URL) [90121-197]
来源是我的Spring Data AuditProvider,具体是这一行:
user = entityManager.createNamedQuery("findUserByUsernameAndTenant", User.class)
.setParameter("tenant", TenantService.DEFAULT_TENANT_ID)
.setParameter("username", UserService.USER_SYSTEM).getSingleResult();
错误仅在执行整个测试套件时发生,而不是仅在运行此测试类时发生。
这里是我正在使用的 TestRunner 等:
@RunWith(SpringRunner.class)
@SpringBootTest
@Transactional
@Rollback
public class MyTest {
这是我的数据源 URL:
spring.datasource.url: 'jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE'
看来“DB_CLOSE_ON_EXIT”并没有解决问题,知道这里发生了什么吗?
更新:
我刚刚意识到,只有在 Eclipse 中运行测试时才会发生这种情况,但它们是在命令行中运行的。虽然我偶尔会得到:
o.s.b.f.support.DisposableBeanAdapter : Invocation of destroy method failed on bean with name 'inMemoryDatabaseShutdownExecutor': org.h2.jdbc.JdbcSQLException: Database is already closed (to disable automatic closing at VM shutdown, add ";DB_CLOSE_ON_EXIT=FALSE" to the db URL)
但我没有得到 PersistenceException 和堆栈跟踪。
【问题讨论】:
-
请注意,默认情况下,当连接关闭时,内存数据库将被丢弃。您可以覆盖此行为。请参阅:Keep H2 in-memory database between connections 和 H2 in-memory database. Table not found
标签: java spring spring-boot junit h2