简体   繁体   中英

Hibernate 4.1 to 5.1 SessionFactory ConnectionProvider

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(); 

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

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM