簡體   English   中英

如何從Java EE 6中的JPA2 EntityManager獲取DataSource或Connection

[英]How to get DataSource or Connection from JPA2 EntityManager in Java EE 6

我有一個工作的應用程序,我使用Java EE 6與EclipseLink進行持久化和PostgreSQL數據庫。

對於User-Registration,我想在PostgreSQL中將密碼設置為:

... password = crypt('inputPassword',gen_salt('bf')) ...

由於我不能使用DigestUtils,我必須手動將用戶插入數據庫。 為了保持我的應用程序可配置,我不想使用InitialContextInstance.lookup(dataSource)查詢DataSource,而是以某種方式從EntityManager中提取它(或連接),如:

DataSource ds = entityManagerInstance.someFunctionThatReturnsADataSourceOrConnection();

或者是否可以使用createNativeQuery或類似的東西與預備語句結合以防止注入?

有時它只需要在谷歌另一次運行:

entityManager.getTransaction().begin();
java.sql.Connection connection = entityManager.unwrap(java.sql.Connection.class);
...
entityManager.getTransaction().commit();

Eclipse鏈接文檔中所述

針對“阿基米德·特拉哈諾”對接受的答案的評論,接受的答案是否適用於除Eclipselink之外的其他答案? 對於至少Hibernate來說,答案是否定的。

當我嘗試接受hibernate的答案時,我收到以下錯誤:

Caused by: org.springframework.orm.jpa.JpaSystemException: Hibernate cannot unwrap interface java.sql.Connection; nested exception is javax.persistence.PersistenceException: Hibernate cannot unwrap interface java.sql.Connection
     at org.springframework.orm.jpa.EntityManagerFactoryUtils.convertJpaAccessExceptionIfPossible(EntityManagerFactoryUtils.java:418) ~[spring-orm-4.0.5.RELEASE.jar:4.0.5.RELEASE]

來自以下stackoverflow問題的答案組合使我能夠提出適用於Hibernate的解決方案。

從無狀態Bean中獲取JDBC Connection對象

Hibernate獲取JasperRunManager的Connection對象

這是我的解決方案:

    Session hibernateSession = entityManager.unwrap(Session.class);

    hibernateSession.doWork(new org.hibernate.jdbc.Work() {

        @Override
        public void execute(Connection connection) throws SQLException {
            // do whatever you need to do with the connection
        }
    });

這是基於dulon的答案,與Hibernate 4一起使用的代碼片段

Connection getConnection() {
        Session session = entityManager.unwrap(Session.class);
        MyWork myWork = new MyWork();
        session.doWork(myWork);
        return myWork.getConnection();
}


private static class MyWork implements Work {

    Connection conn;

    @Override
    public void execute(Connection arg0) throws SQLException {
        this.conn = arg0;
    }

    Connection getConnection() {
        return conn;
    }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM