title: JPA 2.1-portable way to get a Connection instance from Hibernate?
body: <p>I try to get a <code>java.sql.Connection</code> instance with <code>EntityManager.unwrap</code> in a JPA-portable way with Hibernate 5.2.5.Final.</p>
  
  <pre><code>Class&lt;?&gt; databaseDriver = EmbeddedDriver.class;
  File databaseDir = File.createTempFile(NewClass.class.getSimpleName(), null);
  FileUtils.deleteQuietly(databaseDir);
  LOGGER.info(String.format("using '%s' as database directory", databaseDir.getAbsolutePath()));
  String databaseURL = String.format("jdbc:derby:%s", databaseDir.getAbsolutePath());
  Connection connection = DriverManager.getConnection(String.format("%s;create=true", databaseURL));
  connection.close();
  
  EntityManagerFactory entityManagerFactory = null;
  EntityManager entityManager = null;
  try {
      Map&lt;Object, Object&gt; properties = new HashMap&lt;&gt;();
      properties.put("javax.persistence.jdbc.url", databaseURL);
      properties.put("javax.persistence.jdbc.driver", databaseDriver.getName());
      entityManagerFactory = Persistence.createEntityManagerFactory("richtercloud_hibernate-missing-escape-chars_jar_1.0-beta2PU",
              properties);
      entityManager = entityManagerFactory.createEntityManager();
      entityManager.getTransaction().begin();
      connection = entityManager.unwrap(java.sql.Connection.class);
      //do something with connection...
  }finally {
      if(entityManager != null) {
          entityManager.close();
      }
      if(entityManagerFactory != null) {
          entityManagerFactory.close();
      }
  }
  </code></pre>
  
  <p>which fails due to <code>Exception in thread "main" javax.persistence.PersistenceException: Hibernate cannot unwrap interface java.sql.Connection</code>. It works fine in Eclipselink 2.6.4.</p>
  
  <p>I know about the (unportable) possibility to unwrap a Hibernate <code>Session</code> and get a <code>Connection</code> from it, but I'd like to know if there's a portable way.</p>
  
  <p>There's <a href="https://stackoverflow.com/questions/6707115/get-hold-of-a-jdbc-connection-object-from-a-stateless-bean">Get hold of a JDBC Connection object from a Stateless Bean</a>, but it doesn't state explicitly that Hibernate doesn't support this by specification or due to a bug and it's from 2011.</p>