2017-02-22 78 views
0

我試圖在測試期間使用H2嵌入式數據庫和腳本配置來創建和加載數據庫。使用Spring和jdbc填充H2數據庫DataSourceTransactionManager

它工作正常,但當我試圖添加事務支持我的數據庫交互時,我在上下文初始化過程中收到錯誤。

這裏是我的Spring配置:

<bean id="dbcpDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> 
    <property name="driverClassName" value="org.h2.Driver" /> 
    <property name="url" value="jdbc:h2:mem:embeddedH2Database;MODE=Oracle;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE" /> 
    <property name="username" value="sa" /> 
    <property name="password" value="" /> 
</bean> 

<jdbc:embedded-database id="embeddedH2Database" type="H2"> 
    <jdbc:script location="classpath:db/sql/c`enter code here`reate-db.sql" /> 
    <jdbc:script location="classpath:db/sql/insert-data.sql" /> 
</jdbc:embedded-database> 


<tx:advice id="txAdvice" transaction-manager="txManager"> 
    <!-- the transactional semantics... --> 
    <tx:attributes> 
     <tx:method name="*" timeout="60" /> 
    </tx:attributes> 
</tx:advice> 

<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> 
    <property name="dataSource" ref="dbcpDataSource"/> 
</bean> 

<aop:config> 
    <aop:pointcut id="serviceOperation" expression="execution(* x.y.service.*(..))"/> 
    <aop:advisor advice-ref="txAdvice" pointcut-ref="serviceOperation"/> 
</aop:config> 

這裏是bean創建錯誤:

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'embeddedH2Database': Cannot create inner bean '(inner bean)#23bff419' of type [org.springframework.jdbc.datasource.init.CompositeDatabasePopulator] while setting bean property 'databasePopulator'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#23bff419': Cannot create inner bean '(inner bean)#1d2bd371' of type [org.springframework.jdbc.datasource.init.ResourceDatabasePopulator] while setting bean property 'populators' with key [0]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#1d2bd371': Cannot create inner bean '(inner bean)#65fe9e33' of type [org.springframework.jdbc.config.SortedResourcesFactoryBean] while setting bean property 'scripts'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#65fe9e33': Post-processing of FactoryBean's object failed; nested exception is java.lang.AssertionError

回答

0

由於我使用的交易它與執行腳本衝突創建表和裝載數據。

這些腳本需要在沒有應用spring config添加的事務語義的情況下在外部執行。

所以我改變了嵌入式數據庫豆如下刪除腳本元素:

<jdbc:embedded-database id="embeddedH2Database" type="H2"/> 

並補充@sql詮釋我的測試之前創建表和負載表。

@Sql({"classpath:db/sql/create-db.sql", "classpath:db/sql/insert-data.sql"})