spring mvC语言 为@Autowired jdbcTemplate和h2内存数据库执行多次runscript



我继承了一个项目,并试图获得一组针对内存中的h2数据库运行的集成测试。为了让它们传递一些表、关系和引用数据,需要创建。

我可以看到RUNSCRIPT中引用的脚本被多次执行的问题,因此产生Index "XXX_IDX" already exists错误和其他违规。那么,是否有一种方法可以强制脚本只运行一次,或者我需要一个外部数据库?似乎脚本运行在每个连接上,我假设是设计

属性文件

my.datasource.url=jdbc:h2:mem:my_db;DB_CLOSE_DELAY=-1;MODE=Oracle;MVCC=TRUE;INIT=RUNSCRIPT FROM 'classpath:/create-tables-and-ref-data.sql'
XML配置

<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="url" value="${my.datasource.url}"/>
    <!-- other properties for username, password etc... -->
</bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="myDataSource"/>
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="myDataSource"/>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>

以下模式中的许多Java类

@Component
public class SomethingDAOImpl implements SomethingDAO {
  @Autowired
  public SomethingDAOImpl(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
  }
}
@Component
public class SomethingElseDAOImpl implements SomethingElseDAO {
  @Autowired
  public SomethingElseDAOImpl(JdbcTemplate jdbcTemplate) {
    this.jdbcTemplate = jdbcTemplate;
  }
}

默认的bean作用域是单例的,我认为这只是工作,但我想我错过了一些东西。另外,如果我切换到一个已经设置了表和引用数据的真实Oracle实例,测试都通过了。

在许多情况下,可以编写不抛出异常的SQL脚本:

create table if not exists test(id int, name varchar(255));
create index if not exists test_idx on test(name);

我最终使用了另一种方法,因为我无法以一种可以在没有错误的情况下重新应用的方式编写SQL。

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd">
    <jdbc:initialize-database data-source="myDataSource" enabled="true" ignore-failures="ALL">
        <jdbc:script location="classpath:create-and-alter-tables-first-then-add-test-data.sql" />
    </jdbc:initialize-database>
</beans>

在上下文初始化时执行一次。

注意:为简洁起见,省略了其他命名空间和bean

最新更新