You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Assertj-DB提示H2数据库person表不存在问题求助

问题现象
  • Spring Boot应用通过schema.sql初始化了person表,JPA Repository可正常读写,Hibernate日志显示能执行insert into person语句
  • 使用assertj-db 3.0.0连接同一份H2内存数据库时,断言person表存在失败,报错:
[person table] 
Expecting exist but do not exist
java.lang.AssertionError: [person table] 
Expecting exist but do not exist
问题根源

H2内存数据库的mem模式默认是会话隔离的——每个JDBC连接都会创建独立的数据库实例。Spring Boot应用本身的数据源和assertj-db手动创建的连接属于两个不同会话,因此assertj-db无法看到Spring初始化的表结构。

额外注意:H2默认会将未指定大小写规则的表名转为大写,若schema.sql中用小写person创建表,assertj-db查找小写表名时也会匹配失败。

修复方案

提供两种可行修复方式:

方式1:复用Spring数据源(推荐)

直接使用Spring容器中的数据源创建assertj-db连接,避免会话隔离问题:

@Autowired
private DataSource dataSource;

private AssertDbConnection assertDbConnection;

@BeforeEach
void setUp() {
    assertDbConnection = AssertDbConnectionFactory.of(dataSource).create();
}

@Test
public void testPersistPerson() {
    Table personTable = assertDbConnection.table("person").build();
    Assertions.assertThat(personTable).exists();
}

方式2:配置全局共享的H2内存数据库

修改application.yml中的数据源URL,添加参数让所有连接共享同一个数据库实例,并强制表名大小写敏感:

spring:
  datasource:
    url: jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;MODE=MySQL

同时,assertj-db的连接URL必须保持一致:

private AssertDbConnection assertDbConnection = AssertDbConnectionFactory
        .of("jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE;MODE=MySQL", "sa", "")
        .create();

内容的提问来源于stack exchange,提问作者peer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 14:52:18