2016-12-16 104 views
2

我試圖在使用SessionFactory.getCurrentSession()時在Hibernate中獲取Connection對象。在休眠狀態下使用SessionFactory.getCurrentSession()時獲取Connection對象

的源代碼

import java.sql.Connection; 
import java.sql.DatabaseMetaData; 
import java.sql.SQLException; 

import org.hibernate.Session; 
import org.hibernate.SessionFactory; 
import org.hibernate.boot.registry.StandardServiceRegistryBuilder; 
import org.hibernate.cfg.Configuration; 
import org.hibernate.internal.SessionImpl; 

public class SOExample { 
    public static void main(String[] args) throws SQLException { 
     Configuration configuration = new Configuration(); 
     SessionFactory sessionFactory = configuration.buildSessionFactory(new StandardServiceRegistryBuilder().configure().build()); 
     Session session = sessionFactory.getCurrentSession(); 
     Connection connection = ((SessionImpl) session).connection(); 
     // doing operation on connection object as per my requirement 
     DatabaseMetaData databaseMetaData = connection.getMetaData(); 
     System.out.println(databaseMetaData.getDatabaseProductName()); 
    } 
} 

堆棧跟蹤

Exception in thread "main" java.lang.ClassCastException: com.sun.proxy.$Proxy24 cannot be cast to org.hibernate.internal.SessionImpl 
    at com.SOExample.main(SOExample.java:20) 

getCurrentSession()給出SessionProxy對象,因此它不能將它轉換爲SessionImpl那麼什麼是其他方式獲得Connection對象。或如何從代理對象SessionImpl


其他選項我試過但說getConnectionProvider()找不到方法。

SessionFactoryImplementor sessionFactoryImplementation = (SessionFactoryImplementor) session.getSessionFactory(); 
ConnectionProvider connectionProvider = sessionFactoryImplementation.getConnectionProvider(); 
try { 
    Connection connection = connectionProvider.getConnection(); 
} catch (SQLException e) { 
    e.printStackTrace(); 
} 

注意:我使用休眠核心 - 5.0.5.Final.jar

回答

7

Hibenate 5,我們需要做的事情不同的一點(更多詳情檢查https://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html):

import java.sql.Connection; 
import java.sql.SQLException; 

import org.hibernate.Session; 
import org.hibernate.SessionFactory; 
import org.hibernate.boot.registry.StandardServiceRegistryBuilder; 
import org.hibernate.boot.registry.StandardServiceRegistry; 
import org.hibernate.boot.MetadataSources; 
import org.hibernate.boot.Metadata; 
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider; 
import org.hibernate.jdbc.Work; 


public class Htest { 

    public static void main(String ... args) throws SQLException { 
     StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder() 
       .configure("hibernate.cfg.xml") 
       .build(); 

     Metadata metadata = new MetadataSources(standardRegistry) 
       .addAnnotatedClass(TesEntity.class) 
       .buildMetadata(); 

     SessionFactory sessionFactory = metadata.getSessionFactoryBuilder() 
       .build(); 

     //one way to get connection version 5.0.2 
     Connection c = sessionFactory. 
       getSessionFactoryOptions().getServiceRegistry(). 
       getService(ConnectionProvider.class).getConnection(); 

     Session sess = null; 
     try { 
      sess = sessionFactory.getCurrentSession(); 
     } catch (org.hibernate.HibernateException he) { 
      sess = sessionFactory.openSession(); 
     } 


     //If you are using latest version 5.2.3 you can use this line below 
     //Connection c = ((SessionImpl)sess.getSession()).connection(); 
     System.out.println(c.getMetaData().getDatabaseProductName()); 

     //another way to get connection 
     sess.doWork(new Work() { 
      @Override 
      public void execute(Connection connection) throws SQLException { 
       //connection accessible here 
       System.out.println(connection.getMetaData().getDatabaseProductName()); 
      } 
     }); 
    } 
} 

我對德比DB配置,如果你婉測試代碼。

<?xml version='1.0' encoding='utf-8'?> 
<!DOCTYPE hibernate-configuration PUBLIC 
     "-//Hibernate/Hibernate Configuration DTD//EN" 
     "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> 
<hibernate-configuration> 
    <session-factory> 
     <property name="hibernate.connection.driver_class">org.apache.derby.jdbc.ClientDriver</property> 
     <property name="hibernate.connection.url">jdbc:derby://localhost:1527/mytest;create=fasle</property> 
     <!-- <property name="connection.username"/> --> 
     <!-- <property name="connection.password"/> --> 

     <!-- DB schema will be updated if needed --> 
     <!-- <property name="hbm2ddl.auto">update</property> --> 
    </session-factory> 
</hibernate-configuration> 

輸出這個應用程序的:

enter image description here

+0

有沒有其他辦法?我希望它分開,因爲我在其他類和方法中傳遞該對象。 –

+0

我已經更新了代碼。請檢查一下這個解決方案是否可以接受。 –

+0

沒有任何方法'session.getSession()' –