0

How can I get the current connection string or connection from javax.persistence.EntityManager?

The code I tried was

entityManager.getTransaction().begin();
connection=entityManager.unwrap(java.sql.Connection.class);
System.out.print(connection.toString());

persistence.xml contains:

<?xml version="1.0" encoding="UTF-8"?>

<persistence version="2.1"
    xmlns="http://xmlns.jcp.org/xml/ns/persistence" > 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence>  
    http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
    <persistence-unit name="Hibernate_SQLServer" transaction-type = > 
     "RESOURCE_LOCAL">
    <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
    <class>com.dal.es.sqldatabase.dto.AssetDto</class>
    <class>com.dal.es.sqldatabase.dto.CasinoDto</class>  

    <properties>
     <property name="javax.persistence.jdbc.driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
    <property name="javax.persistence.jdbc.url" value="jdbc:sqlserver://xx.x.xxx.xxx\\sql2012:1433;databaseName=Casino" />
    <property name="javax.persistence.jdbc.user" value="sa" />
    <property name="javax.persistence.jdbc.password" value="abc@1234" />
    <property name="hibernate.show_sql" value="true" />
    <property name="eclipselink.ddl-generation" value="create-tables" />
   <property name="eclipselink.ddl-generation.output-mode" value="database" /
  </properties>

The unwrap method throws a Hibernate cannot unwrap interface java.sql.Connection exception.

I tried the solution posted in the link below, but was not successful in obtaining the connection string. Getting Database connection in pure JPA setup

mprabhat
  • 20,107
  • 7
  • 46
  • 63
Indu
  • 95
  • 2
  • 8

1 Answers1

1

You can not unwrap Connection object from entityManager, what you need to do is unwrap Session object first and then get Connection using Work API.

Below code snippet does exactly the same.

Connection connection = entityManager.unwrap(Session.class).doReturningWork(conn -> conn);
try {
    DatabaseMetaData metaData = connection.getMetaData();
    String url = metaData.getURL();
} catch (SQLException e) {
    e.printStackTrace();
}

Since you need connection string, you can get it from Metadata.

eatSleepCode
  • 4,427
  • 7
  • 44
  • 93