I try to get a java.sql.Connection
instance with EntityManager.unwrap
in a JPA-portable way with Hibernate 5.2.5.Final.
Class<?> 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<Object, Object> properties = new HashMap<>();
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();
}
}
which fails due to Exception in thread "main" javax.persistence.PersistenceException: Hibernate cannot unwrap interface java.sql.Connection
. It works fine in Eclipselink 2.6.4.
I know about the (unportable) possibility to unwrap a Hibernate Session
and get a Connection
from it, but I'd like to know if there's a portable way.
There's Get hold of a JDBC Connection object from a Stateless Bean, but it doesn't state explicitly that Hibernate doesn't support this by specification or due to a bug and it's from 2011.