首页 > 解决方案 > 如何从 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 设置中获取数据库连接

标签: springspring-data-jpa

解决方案


你不能unwrap Connection反对entityManager,你需要做的是unwrap Session先反对,然后再Connection使用WorkAPI​​。

下面的代码片段完全一样。

Connection connection = entityManager.unwrap(Session.class).doReturningWork(conn -> conn);
try {
    DatabaseMetaData metaData = connection.getMetaData();
    String url = metaData.getURL();
} catch (SQLException e) {
    e.printStackTrace();
}

由于您需要连接字符串,您可以从Metadata.


推荐阅读