gpt4 book ai didi

java - JPA 2.1-从 Hibernate 获取 Connection 实例的可移植方法?

转载 作者:行者123 更新时间:2023-12-01 16:46:06 25 4
gpt4 key购买 nike

我尝试使用 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();
}
}

由于线程“main”javax.persistence.PersistenceException中出现异常:Hibernate无法解开接口(interface)java.sql.Connection而失败。它在 Eclipselink 2.6.4 中运行良好。

我知道打开 Hibernate Session 并从中获取 Connection 的(不可移植)可能性,但我想知道是否有一种可移植的方法。

Get hold of a JDBC Connection object from a Stateless Bean ,但它没有明确指出 Hibernate 根据规范或由于错误而不支持此功能,并且它是从 2011 年开始的。

最佳答案

既然你提到了 JPA,我假设你正在使用 j2ee。

首先看看这是否有帮助:How can i get the session object if i have the entitymanager

如果这没有帮助,我可以解释如何获得与 Wildfly 9 和 8 的连接。您应该将 postgresql 数据源定义为您的standalone.xml。然后就可以通过下面的java代码来访问:

import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.*;
import javax.sql.DataSource;

public class ConnectionFactory {
/**
* 'getConnection' method returns the JDBC connection from the DataSource.
*
* @return a value of type 'Connection'
* @exception SQLException if an error occurs
*/
public static Connection getConnection() throws SQLException{
return getDBConnection().getConnection();
}


public static DataSource getDBConnection() throws SQLException{
return getDataSource("java:jboss/datasources/PostgreSQLDS"); // jndi
}

}

下面是我们的 postgresql 数据源的示例 xml 片段。只需将环境变量设置为您需要的即可:

        <datasource jta="true" jndi-name="java:jboss/datasources/PostgreSQLDS" pool-name="PostgreSQLDS" enabled="true" use-java-context="true" use-ccm="true">
<connection-url>jdbc:postgresql://${env.OPENSHIFT_POSTGRESQL_DB_HOST}:${env.OPENSHIFT_POSTGRESQL_DB_PORT}/${env.OPENSHIFT_APP_NAME}</connection-url>
<driver>postgresql</driver>
<new-connection-sql>select 1</new-connection-sql>
<pool>
<min-pool-size>10</min-pool-size>
<max-pool-size>50</max-pool-size>
<!--idle-timeout-minutes>1</idle-timeout-minutes> Default is 15 mins -->
<prefill>true</prefill>
<flush-strategy>IdleConnections</flush-strategy>
</pool>
<security>
<user-name>${env.OPENSHIFT_POSTGRESQL_DB_USERNAME}</user-name>
<password>${env.OPENSHIFT_POSTGRESQL_DB_PASSWORD}</password>
</security>
<validation>
<check-valid-connection-sql>SELECT 1</check-valid-connection-sql>
<background-validation>true</background-validation>
<validate-on-match>true</validate-on-match>
</validation>
<statement>
<track-statements>true</track-statements> <!-- Warn when statements and result sets not closed -->
<prepared-statement-cache-size>100</prepared-statement-cache-size>
<share-prepared-statements>true</share-prepared-statements>
</statement>
</datasource>

关于java - JPA 2.1-从 Hibernate 获取 Connection 实例的可移植方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41710164/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com