【问题标题】:JPA 2.1-portable way to get a Connection instance from Hibernate?从 Hibernate 获取 Connection 实例的 JPA 2.1-portable 方式?
【发布时间】:2017-06-02 06:50:44
【问题描述】:

我尝试使用 Hibernate 5.2.5.Final 以 JPA 可移植方式获取带有 EntityManager.unwrapjava.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();
    }
}

由于Exception in thread "main" javax.persistence.PersistenceException: Hibernate cannot unwrap interface java.sql.Connection 而失败。它在 Eclipselink 2.6.4 中运行良好。

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

Get hold of a JDBC Connection object from a Stateless Bean,但它没有明确说明 Hibernate 不支持此规范或由于错误,它是从 2011 年开始的。

【问题讨论】:

    标签: java hibernate jpa jpa-2.1


    【解决方案1】:

    既然您提到了 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 sn-p 如下所示。只需将环境变量设置为您需要的:

            <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>
    

    【讨论】:

    • 这与提出的问题无关。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-20
    • 1970-01-01
    • 1970-01-01
    • 2014-05-27
    • 2021-09-25
    相关资源
    最近更新 更多