【发布时间】:2017-06-02 06:50:44
【问题描述】:
我尝试使用 Hibernate 5.2.5.Final 以 JPA 可移植方式获取带有 EntityManager.unwrap 的 java.sql.Connection 实例。
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();
}
}
由于Exception in thread "main" javax.persistence.PersistenceException: Hibernate cannot unwrap interface java.sql.Connection 而失败。它在 Eclipselink 2.6.4 中运行良好。
我知道打开 Hibernate Session 并从中获取 Connection 的(不可移植的)可能性,但我想知道是否有可移植的方式。
有 Get hold of a JDBC Connection object from a Stateless Bean,但它没有明确说明 Hibernate 不支持此规范或由于错误,它是从 2011 年开始的。
【问题讨论】:
标签: java hibernate jpa jpa-2.1