I have a project where I am using spring-data-jpa with Hibernate and I am writing an integration test which uses an H2 in memory database.
In my DB Script, after the table creation, I am actually run a few insert statements
INSERT INTO COST (paymentType, costValue, costCategory) VALUES ('INTERNATIONAL', 100, 'LICENSES');
INSERT INTO COST (paymentType, costValue, costCategory) VALUES ('INTERNATIONAL', 20, 'HARDWARE');
After running my integration test, I saw that there were 4 entries returned instead of the 2.
The logs confirmed that the test was initialising the datasource twice and I'd like to understand why. Any help would be appreciated.
2017-04-26 12:19:38; LOG_LEVEL="DEBUG"; SOURCE="org.springframework.jdbc.datasource.DriverManagerDataSource"; EVENT_MESSAGE="Creating new JDBC DriverManager Connection to [jdbc:h2:mem:test;DB_CLOSE_DELAY=-1;INIT=RUNSCRIPT FROM 'classpath:create-db.sql']"
In my Spring config file, annotated with @EnableJpaRepositories, I then create the persistence related beans as shown below
@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;
}
The properties are
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
Cheers Kris