...without actually reading and parsing the persistence.xml
I can retrieve the name of the persistence unit of an EntityManager
using the p
DataSource dataSource = (DataSource)
em.getEntityManagerFactory().getProperties()
.get(org.hibernate.cfg.AvailableSettings.JPA_JTA_DATASOURCE);
You can retrieve datasoure with hibernate. Tested with Hibernate 5.3
In a Spring environment you can use this:
import org.springframework.orm.jpa.EntityManagerFactoryInfo;
...
@PersistenceContext
EntityManager entityManager;
public DataSource getDataSourceFromHibernateEntityManager() {
EntityManagerFactoryInfo info = (EntityManagerFactoryInfo) entityManager.getEntityManagerFactory();
return info.getDataSource();
}
in SpringBoot environment you can use the following:
@PersistenceContext
EntityManager entityManager;
private HikariDataSource getDataSourceFromHibernateEntityManager() {
EntityManagerFactoryInfo info = (EntityManagerFactoryInfo) entityManager.getEntityManagerFactory();
return (HikariDataSource) info.getDataSource();
}
public String getDataSourceProperties() {
HikariDataSource dataSource = getDataSourceFromHibernateEntityManager();
return "DataSource properties:" +
"URL: " + dataSource.getJdbcUrl() + "\n" +
"Default Schema: " + dataSource.getPoolName() + "\n" +
"Driver Class Name: " + dataSource.getDriverClassName() + "\n" +
"Username: " + dataSource.getUsername() + "\n";
}
Here's what helped me. I use HikariCP but I don't think it matters.
Basically what needs to be done is
org.hibernate.engine.jdbc.connections.spi.ConnectionProvider
classjavax.sql.DataSource
.Service registry can be retrieved from EntityManager
((SessionImpl) em).getFactory().getServiceRegistry()
or from EntityManagerFactory directly
((SessionFactoryImpl) entityManagerFactory).getServiceRegistry()