我正在尝试使用H2嵌入式数据库在Spring Boot 2.1.4中进行junit测试。我面临一个特殊的序列问题。所以根据spring boot和h2教程,我有一个schema.sql脚本来生成我的相关表:
create sequence seq_test increment by 50;
我可以看到从调试日志调用创建序列。
为了测试序列是否正常工作,我在它上面运行了一个nextval()但得到了一个表seq_test没有创建错误。这只发生在序列中,当我查询普通表时,我得到了一个正确的结果。
测试用例:
@RunWith(SpringRunner.class)
@ActiveProfiles("test")
@SpringBootTest
@Import({EmbeddedRedis.class, EmbeddedRabbitMQ.class})
@Slf4j
public class ProfileCreationTests {
@Autowired
private EntityManager em;
@Test
public void profileCreationTest() {
Query query = em
.createNativeQuery("SELECT NEXTVAL(seq_test)");
log.info(query.getSingleResult().toString());
log.info(em.createNativeQuery("SELECT count(*) FROM tbl_test").getSingleResult().toString());
}
}
第一行错误输出,如果我将其注释掉,第二个查询运行正常。
app config:spring:profiles:test h2:console:enabled:true jpa:hibernate:use-new-id-generator-mappings:true
试试Query query = em.createNativeQuery("call next value for seq_test");
h2提供不同的compatibility modes,并且获取下一个值的语法在它们之间不同。我认为当没有选择兼容模式时,上面的语法很好。