I'm trying to get Connection object in Hibernate when SessionFactory.getCurrentSession() is used.
Source code
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());
}
}
Stacktrace
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() gives Proxy object of Session so It can't cast it to SessionImpl so what are the other ways to get Connection object. Or How to SessionImpl from Proxy object.
Other option I tried but it says getConnectionProvider() method not found.
SessionFactoryImplementor sessionFactoryImplementation = (SessionFactoryImplementor) session.getSessionFactory();
ConnectionProvider connectionProvider = sessionFactoryImplementation.getConnectionProvider();
try {
Connection connection = connectionProvider.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
Note: I'm using hibernate-core-5.0.5.Final.jar
