I have an app which is using hibernate and jpa. I need to find out which db it is connected to so that some native sql query i execute based on db say for eg. oracle and postgre
As a workaround, you can fetch the EntityManagerFactory
properties to get the underlying database configuration, which is implementation specific.
Hibernate : hibernate.connection.driver_class
EclipseLink : eclipselink.target-database
This property specifies the target database. In your case, it may have value as Oracle
or PostgreSQL
for respective database.
General : javax.persistence.jdbc.driver
From this information, you can get the database currently connected.
EntityManagerFactory emf = entityManager.getEntityManagerFactory();
Map emfProperties = emf.getProperties();
String driverClass = (String)emfProperties.get(PROPERTY);
//-- For PostgreSQL, it will have value "org.postgresql.Driver"
if(driverClass.lastIndexOf("postgresql") != -1)
postGreSQL_DB = true;
Note : Not much clear on your application design, but it may happen that your application is connected to both the databases. If possible, you can try having separate EntityManager
for each database, pointing to different persistence units in persistence.xml
& can use it accordingly.
If this is not the case & only one of them is connected at a time, then you can simply verify it by entityManager.isOpen()
or emf.isOpen()
.
Edit :
Connection connection = entityManager.unwrap(Connection.class);
DatabaseMetaData metaData = connection.getMetaData();
Now from this, you can get database product name, driver etc.