简体   繁体   English

Hibernate 4.1 到 5.1 SessionFactory ConnectionProvider

[英]Hibernate 4.1 to 5.1 SessionFactory ConnectionProvider

How could I obtain the connection provider from a session factory in hibernate 5?如何从休眠 5 中的会话工厂获取连接提供程序? The method to obtain the connection does not exist anymore and is not replaced by anything in the javadocs.获取连接的方法不再存在,也不会被 javadocs 中的任何内容替换。 This code snippet worked in 4.1, but in 5.1 it does not (specifically, getConnectionProvider() does not exist).此代码片段在 4.1 中有效,但在 5.1 中无效(特别是 getConnectionProvider() 不存在)。

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:对于休眠 5.2.10,试试这个:

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

See:见:

Hibernate - Deprecated API Hibernate - 不推荐使用的 API

Docs Hibernate 4.1 - SessionFactoryImplementor.getConnectionProvider() 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.正如 Allinger Medeiros 所说,ConnectionProvider 在 Hibernate 4 中已弃用,在 Hibernate 5 中不可用。但是,正如 Gwaptiva 指出的那样,他的解决方案会导致 ClassCastException。

This worked for me:这对我有用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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