在内存数据库中使用 H2 进行 Spring 测试截断所有表

Fel*_*yta 5 java mysql spring spring-mvc h2

我是一名计算机科学专业的大三学生,正在使用 Spring 进行 MVC 项目,而且我对 Spring 还很陌生。

我在内存db中设置了一个H2并编写了2个sql脚本;一个用于填充数据库,另一个用于将其清空。

据我所知,truncate table <table name>delete from <table name>truncate table 之间的实际区别是 ddl,因此它更快,并且它还会重置自动递增列。问题是H2的截断表不会重置自动递增列。你能指出我哪里搞砸了吗?

我正在使用 spring 的 SqlGroup 注释来运行脚本。

@SqlGroup({
    @Sql(executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD, scripts = 
                                                "classpath:populate.sql"),
    @Sql(executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD, scripts = 
                                                  "classpath:cleanup.sql")
})
Run Code Online (Sandbox Code Playgroud)

这是应该截断每个表的 cleanup.sql。

SET FOREIGN_KEY_CHECKS=0;

TRUNCATE TABLE `criteria`;
TRUNCATE TABLE `job_title`;
TRUNCATE TABLE `organization`;
TRUNCATE TABLE `organization_teams`;
TRUNCATE TABLE `organization_users`;
TRUNCATE TABLE `organization_job_titles`;
TRUNCATE TABLE `review`;
TRUNCATE TABLE `review_evaluation`;
TRUNCATE TABLE `team`;
TRUNCATE TABLE `team_members`;
TRUNCATE TABLE `user`;
TRUNCATE TABLE `user_criteria_list`;

SET FOREIGN_KEY_CHECKS=1;
Run Code Online (Sandbox Code Playgroud)

populate.sql 只是将一堆行插入到这些表中,而不会违反完整性约束。

因此,当我运行测试类时,只有第一个方法通过。其余的我得到这样的东西:

参照完整性约束违规:“FK3MAB5XYC980PSHDJ3JJ6XNMMT:PUBLIC.ORGANIZATION_JOB_TITLES FOREIGN KEY(JOB_TITLES_ID) REFERENCES PUBLIC.JOB_TITLE(ID) (1)”;SQL 语句:INSERT INTO organization_job_titles(organization_id, job_titles_id) VALUES(1, 1)

我认为问题是由于自动递增列未重置而引起的。所以我写了一个不同的测试类:

monAutoIncTest.java

 @Sql(executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD, scripts =
    "classpath:truncateTable.sql")
    public class monAutoIncTest {
        @Autowired
        OrganizationService organizationService;

        @Test
            public void h2truncate_pls() throws BaseException {
            organizationService.add(new Organization("Doogle"));
            Organization fetched = organizationService.getByName("Doogle");
            Assert.assertEquals(1, fetched.getId());
        }

        @Test
        public void h2truncate_plz() throws BaseException {
            organizationService.add(new Organization("Zoogle"));
            Organization fetched = organizationService.getByName("Zoogle");
            Assert.assertEquals(1, fetched.getId());
        }
    } 
Run Code Online (Sandbox Code Playgroud)

使用 truncateTable.sql

SET FOREIGN_KEY_CHECKS=0;

TRUNCATE TABLE `organization`;

SET FOREIGN_KEY_CHECKS=1;
Run Code Online (Sandbox Code Playgroud)

当测试运行时,无论哪个方法先运行都会通过,另一个方法给我这个。

java.lang.AssertionError:预期:1 实际:2

Kon*_*bun 3

目前 H2 不支持该功能,但我们可以在他们的路线图中看到此类计划

TRUNCATE 应该像 MySQL 和 MS SQL Server(以及可能的其他数据库)中一样重置标识列。

尝试将此语句与以下内容组合使用TRUNCATE

ALTER TABLE [table] ALTER COLUMN [column] RESTART WITH [initial value]
Run Code Online (Sandbox Code Playgroud)

  • H2 v1.4.199 现在支持 TRUNCATE TABLE [table] RESTART IDENTITY;https://h2database.com/html/commands.html#truncate_table (2认同)