1

How could I obtain the connection provider from a session factory in hibernate 5? The method to obtain the connection does not exist anymore and is not replaced by anything in the javadocs. This code snippet worked in 4.1, but in 5.1 it does not (specifically, getConnectionProvider() does not exist).

private SessionFactory factory;


private ServletOutputStream outputStream;

private ServletContext context;

public Object execute(Map properties) {
    InputStream input = null;
    try {
        Session session = factory.getCurrentSession();

        SessionFactoryImplementor sessionFactoryImplementation = (SessionFactoryImplementor) session.getSessionFactory();
        ConnectionProvider connectionProvider = sessionFactoryImplementation).getConnectionProvider();
        Connection conn = connectionProvider.getConnection(); 

2 Answers 2

1

For hibernate 5.2.10 try this:

public Connection getConnection(){        
    try {
        return ((SessionImplementor) sessionFactory).getJdbcConnectionAccess()
                .obtainConnection();
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return null;
}  

See:

Hibernate - Deprecated API

Docs Hibernate 4.1 - SessionFactoryImplementor.getConnectionProvider()

1
  • 1
    Other than that that results in a ClassCastException
    – Gwaptiva
    Commented Jul 25, 2019 at 11:23
0

As Allinger Medeiros said, ConnectionProvider is deprecated in Hibernate 4 and not available in Hibernate 5. However, as Gwaptiva pointed out, his solution results in a ClassCastException.

This worked for me:

JdbcConnectionAccess connectionAccess = 
    ((SessionImplementor)sessionFactory.getCurrentSession())
    .getJdbcConnectionAccess();

Not the answer you're looking for? Browse other questions tagged or ask your own question.