我有一個項目,我在Hibernate中使用spring-data-jpa,我正在編寫一個在內存數據庫中使用H2的集成測試。Spring-Data-Jpa DriverManagerDataSource初始化兩次
在我的數據庫腳本,創建表後,我居然跑幾個insert語句
INSERT INTO COST (paymentType, costValue, costCategory) VALUES ('INTERNATIONAL', 100, 'LICENSES');
INSERT INTO COST (paymentType, costValue, costCategory) VALUES ('INTERNATIONAL', 20, 'HARDWARE');
運行我的集成測試後,我看到有4個條目返回的2
代替日誌證實測試正在初始化數據源兩次,我想明白爲什麼。任何幫助,將不勝感激。
2017-04-26 12:19:38; LOG_LEVEL = 「DEBUG」; SOURCE = 「org.springframework.jdbc.datasource.DriverManagerDataSource」; EVENT_MESSAGE = 「創建新的JDBC的DriverManager連接到[JDBC:H2:MEM:測試; DB_CLOSE_DELAY = -1; INIT = RUNSCRIPT FROM '類路徑:創db.sql']」
在我的Spring配置文件,與@EnableJpaRepositories註釋,我然後創建相關豆持久性如下所示
@Bean
public JpaTransactionManager transactionManager() {
if (transactionManager == null) {
transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
}
return transactionManager;
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
if (entityManagerFactoryBean == null) {
entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(dataSource());
entityManagerFactoryBean.setPersistenceProviderClass(HibernatePersistenceProvider.class);
entityManagerFactoryBean.setPackagesToScan(env.getRequiredProperty(ENTITYMANAGER_PACKAGES_TO_SCAN));
entityManagerFactoryBean.setJpaProperties(hibProperties());
}
return entityManagerFactoryBean;
}
@Bean
public DriverManagerDataSource dataSource() {
if (dataSource == null) {
dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getRequiredProperty(DATABASE_DRIVER));
dataSource.setUrl(env.getRequiredProperty(DATABASE_URL));
dataSource.setUsername(env.getRequiredProperty(DATABASE_USERNAME));
dataSource.setPassword(env.getRequiredProperty(DATABASE_PASSWORD));
}
return dataSource;
}
的屬性是
db.driver = org.h2.Driver
db.url = jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;INIT=RUNSCRIPT FROM \'classpath:create-db.sql\'
db.username = cost
db.password = cost
entitymanager.packages.to.scan = com.somecompany.cost
hibernate.dialect = org.hibernate.dialect.H2Dialect
hibernate.show_sql = false
hibernate.format_sql = false
乾杯 克里斯
你會告訴你hibProperties()方法,和你的DATABASE_URL –
我已經編輯原始帖子,包括他們..謝謝 – krisrr3