【发布时间】:2019-04-23 15:58:30
【问题描述】:
如何从 javax.persistence.EntityManager 获取当前连接字符串或连接?
我试过的代码是
entityManager.getTransaction().begin();
connection=entityManager.unwrap(java.sql.Connection.class);
System.out.print(connection.toString());
persistence.xml 包含:
<?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>
unwrap 方法抛出 Hibernate cannot unwrap interface java.sql.Connection 异常。
我尝试了下面链接中发布的解决方案,但没有成功获取连接字符串。 Getting Database connection in pure JPA setup
【问题讨论】:
-
你在使用休眠吗?
-
不是直接的。我使用 org.hibernate.jpa.HibernatePersistenceProvider
-
使用 entityManager.unwrap(Session.class) 其中 Session 是休眠的会话类。这将使您返回休眠状态的会话。
-
@Indu 我的回答中给出的解决方案对你有用吗?