我正在为我的数据库集成测试使用以下配置:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring/spring-master.xml"})
@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = false)
@Transactional()
public class EmployeeAccessPropertyTest {
spring-master.xml按以下顺序加载 spring 配置文件:
<import resource="classpath:spring/db/dev-datasource-config.xml"/>
<import resource="classpath:spring/db/jpa-config.xml"/>
<import resource="classpath:spring/db/transaction-config.xml"/>
<import resource="classpath:spring/db/component-config.xml"/>
dev-datasource-config.xml定义 dataSource 并通过 liquibase 初始化 db 方案:
<context:property-placeholder location="classpath:db/config/dev-data-access.properties"/>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<bean id="liquibase" class="liquibase.integration.spring.SpringLiquibase">
<property name="dataSource" ref="dataSource" />
<property name="changeLog" value="classpath:db/changelog/db.changelog-master.xml" />
<property name="dropFirst" value="true" />
</bean>
现在,当我运行测试时,我收到以下错误:
javax.persistence.PersistenceException: [PersistenceUnit: studentPersistenceUnit] Unable to build EntityManagerFactory
...
Caused by: org.hibernate.HibernateException: Missing table: employees
似乎,初始化 entityManagerFactory 时(在jpa-config.xml文件中)没有创建表。好的,我首先通过 liquibase maven 插件生成方案:
mvn initialize liquibase:update
通过 Spring 上下文注释以下数据库方案生成:
<!--<bean id="liquibase" class="liquibase.integration.spring.SpringLiquibase">-->
<!--<property name="dataSource" ref="dataSource" />-->
<!--<property name="changeLog" value="classpath:db/changelog/db.changelog-master.xml" />-->
<!--<property name="dropFirst" value="true" />-->
<!--</bean>-->
问题消失了。我该怎么做才能确保 Spring 首先加载 dev-datasource-config.xml,初始化 liquibase bean,然后才加载 jpa-config.xml,其中如下所示:
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="dataSource"/>