【问题标题】:Spring: Table already exists error! @DirtiesContext and EmbeddedDatabaseBuilder doesn work together?Spring:表已经存在错误! @DirtiesContext 和 EmbeddedDatabaseBuilder 不能一起工作吗?
【发布时间】:2018-10-29 01:04:20
【问题描述】:

我在运行 junit 测试类时遇到了一些错误。

这是我的测试课。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=TestApplicationContext.class)
@DirtiesContext(classMode=ClassMode.AFTER_EACH_TEST_METHOD)
public class UserDaoTestDrive {

    @Autowired
    private UserDao dao;

这是我用于配置的 java 类。

@Configuration
@EnableTransactionManagement
public class TestApplicationContext {
...
    @Bean
    public DataSource embeddedDatabase() {

        return new EmbeddedDatabaseBuilder().setName("embeddedDatabase").setType(HSQL).addScript("classpath:springbook/user/sqlservice/updatable/sqlRegistrySchema.sql").build();
    }

这是错误信息。

Error creating bean with name 'embeddedDatabase' defined in class springbook.TestApplicationContext: 
Instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanDefinitionStoreException: 
Factory method [public javax.sql.DataSource springbook.TestApplicationContext.embeddedDatabase()] threw exception; 
nested exception is org.springframework.dao.DataAccessResourceFailureException: Failed to execute database script;
...Caused by: java.sql.SQLException: Table already exists

我有这个奇怪的test result,它在所有其他测试方法中都失败了。 我有 7 种测试方法,1,3,5,7 总是成功,2,4,6 总是失败。

我不知道为什么会出现这些错误,因为当我使用 XML 文件进行上下文配置时,我的测试类运行良好

我的 XML 文件是这样的。

<jdbc:embedded-database id="embeddedDatabase" type="HSQL">
  <jdbc:script location="classpath:springbook/user/sqlservice/updatable.sqlRegistrySchema.sql" />
<jdbc:embedded-database>

sqlRegistrySchema 文件

CREATE TABLE  SQLMAP(
KEY_ VARCHAR(100) PRIMARY KEY,
SQL_ VARCHAR(100) NOT NULL);

谁能告诉我为什么?

我猜嵌入式数据库不会在每个测试方法完成后立即关闭。

【问题讨论】:

  • 能否请您发布您的updatable.sqlRegistrySchema.sql?
  • CREATE TABLE SQLMAP(KEY_VARCHAR(100) PRIMARY KEY, SQL_VARCHAR(100) NOT NULL);

标签: java spring embedded-database


【解决方案1】:

我建议在你的 sql 脚本中尝试 CREATE TABLE IF NOT EXISTS。看起来 DB 挂在内存的某个地方。

【讨论】:

    猜你喜欢
    • 2018-12-24
    • 2019-04-28
    • 2017-02-28
    • 2015-11-24
    • 1970-01-01
    • 1970-01-01
    • 2018-04-14
    • 1970-01-01
    相关资源
    最近更新 更多