Get published DataSource from EntityManager

Update DataSourceInitializedPublisher to always attempt to obtain the
published DataSource directly from the EntityManager. In the case where
the EntityManager doesn't provide a DataSource, the previous logic is
used.

Fixes gh-8296
This commit is contained in:
Phillip Webb 2017-03-01 20:40:20 -08:00
parent 055542f2b4
commit 57111aba22

View File

@ -1,5 +1,5 @@
/*
* Copyright 2012-2014 the original author or authors.
* Copyright 2012-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@ -64,20 +64,33 @@ class DataSourceInitializedPublisher implements BeanPostProcessor {
if (bean instanceof JpaProperties) {
this.properties = (JpaProperties) bean;
}
if (bean instanceof EntityManagerFactory && this.dataSource != null
&& isInitializingDatabase()) {
this.applicationContext
.publishEvent(new DataSourceInitializedEvent(this.dataSource));
if (bean instanceof EntityManagerFactory) {
publishEventIfRequired((EntityManagerFactory) bean);
}
return bean;
}
private boolean isInitializingDatabase() {
private void publishEventIfRequired(EntityManagerFactory entityManagerFactory) {
DataSource dataSource = findDataSource(entityManagerFactory);
if (dataSource != null && isInitializingDatabase(dataSource)) {
this.applicationContext
.publishEvent(new DataSourceInitializedEvent(dataSource));
}
}
private DataSource findDataSource(EntityManagerFactory entityManagerFactory) {
Object dataSource = entityManagerFactory.getProperties()
.get("javax.persistence.nonJtaDataSource");
return (dataSource != null && dataSource instanceof DataSource
? (DataSource) dataSource : this.dataSource);
}
private boolean isInitializingDatabase(DataSource dataSource) {
if (this.properties == null) {
return true; // better safe than sorry
}
Map<String, String> hibernate = this.properties
.getHibernateProperties(this.dataSource);
.getHibernateProperties(dataSource);
if (hibernate.containsKey("hibernate.hbm2ddl.auto")) {
return true;
}