spring - 如何从 javax.persistence.EntityManger 获取连接字符串
问题描述
如何从 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 异常。
我尝试了下面链接中发布的解决方案,但未能成功获取连接字符串。 在纯 JPA 设置中获取数据库连接
解决方案
你不能unwrap
Connection
反对entityManager
,你需要做的是unwrap
Session
先反对,然后再Connection
使用Work
API。
下面的代码片段完全一样。
Connection connection = entityManager.unwrap(Session.class).doReturningWork(conn -> conn);
try {
DatabaseMetaData metaData = connection.getMetaData();
String url = metaData.getURL();
} catch (SQLException e) {
e.printStackTrace();
}
由于您需要连接字符串,您可以从Metadata
.
推荐阅读
- mysql - 需要正确的 SQL 查询
- python - 在循环中对 pandas 列的所有值求和
- .net-core - 使用 IOptions<> 将应用程序设置注入 Azure Functions v3.0
- css - 防止 mask-img 屏蔽滚动条
- xamarin - 如果我的 Xamarin 应用程序在未连接到数据库时崩溃,appcenter 是否仍会获取崩溃数据?
- javascript - NodeJs Check Phase 在计时器阶段完成之前调用
- reactjs - 如何在待办事项应用中删除已完成的列表项?
- mysql - 如何在 Visual Basic 标签中打印 mysql 数据
- android - 如何防止我的网站以 android 的浏览器桌面模式打开?
- c# - 如何使用按钮轻推 Winforms 标签?