【问题标题】:How to obtain the connection string from javax.persistence.EntityManger如何从 javax.persistence.EntityManager 获取连接字符串
【发布时间】: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 我的回答中给出的解决方案对你有用吗?

标签: spring spring-data-jpa


【解决方案1】:

你不能unwrapConnection对象来自entityManager,你需要做的是先unwrapSession对象然后使用Work API获取Connection

下面的代码 sn-p 完全一样。

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

由于需要连接字符串,可以从Metadata获取。

【讨论】:

    猜你喜欢
    • 2022-12-13
    • 2011-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多