java - Spring ScriptUtils : with MySql causes tests to freeze forever

标签 java mysql spring

我正在尝试根据 Spring Boot 测试环境中的 Activity 配置文件(h2 或 mysql)执行不同的 sql 脚本。这是我尝试使用 MySql 执行的导致卡住的测试用例:

@RunWith(SpringRunner.class)
@DataJpaTest
@AutoConfigureTestDatabase(replace= AutoConfigureTestDatabase.Replace.NONE)
public class EntityRepositoryTestIT {

    @Autowired
    EntityRepository entityRepository;

    @Autowired
    private DataSource dataSource;

    @Value("${spring.profiles.active}")
    private String profile;

    @After
    public void after() throws Exception {
        ScriptUtils.executeSqlScript(dataSource.getConnection(),
                new ClassPathResource("/scripts/test_data_clear_"+profile+".sql"));
    }


    @Test
    @Sql(scripts = "/scripts/test_data.sql", executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
    public void findAllTest() throws Exception {
        Assert.assertEquals(7, entityRepository.findAll().size());
    }

}

启用 DEBUG 的 org.springframework.jdbc 上的记录器显示在调用此行时发生卡住:

ALTER TABLE entity AUTO_INCREMENT = 1;

这仅在 MySql 上失败,而在 H2 上工作正常:

ALTER TABLE entity ALTER COLUMN id RESTART WITH 1;

测试在 MySql 上再次正常工作通过使用注释:

@Sql(scripts = "/scripts/test_data_clear_mysql.sql", executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)

@sql 注释似乎比 ScriptUtils 的编程调用添加了更多逻辑。使用 H2,ScriptUtils 和 @sql 注释都可以顺利工作。

问题是注释不允许动态更改执行的 sql 脚本,它的 'scripts' 参数是一个编译时间常量。

任何有关如何使其工作的建议将不胜感激!

最佳答案

我的直觉是您根本没有正确关闭/返回数据库连接。

@After
public void after() throws Exception {
    try (Connection connection = dataSource.getConnection()) {
        if (connection != null) {
            ScriptUtils.executeSqlScript(connection,
                new ClassPathResource("/scripts/test_data_clear_"+profile+".sql"));
            log.info("SQL script successful");
        } else {
            log.warn("!!! No connection available !!!");
        }
    }
}

即将您的连接包装在 try-catch-resources block 中,以便关闭连接(如果您使用的是数据库池,则返回到池中,例如 Hikari)。

关于java - Spring ScriptUtils : with MySql causes tests to freeze forever,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52129294/

相关文章:

java - 如何将 bean 注入(inject)作用域实现?

java - android 中的 SimpleDateFormat 错误

java - 过度使用 Application 类来存储持久数据

java - 无法匹配 Java 中的正则表达式

mysql - 这个sql命令有什么语法错误?

mysql - 一个 SQL 查询来获取距离给定坐标一定距离内的所有城市?

Spring MVC : how to handle incoming request to wrong context path

java - 如何正确设置 @OneToOne 与 JPA Hibernate 的关系?

Java:单台 PC 上出现奇怪的字符串/整数错误

php - excel导出数据时如何不打印重复数据?