【问题标题】:Hibernate 4.1 to 5.1 SessionFactory ConnectionProviderHibernate 4.1 到 5.1 SessionFactory ConnectionProvider
【发布时间】:2017-06-02 13:46:50
【问题描述】:

如何从 hibernate 5 中的会话工厂获取连接提供程序?获取连接的方法不再存在,并且不会被 javadocs 中的任何内容替换。此代码 sn-p 在 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(); 

【问题讨论】:

    标签: java hibernate jakarta-ee


    【解决方案1】:

    对于休眠 5.2.10 试试这个:

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

    见:

    Hibernate - Deprecated API

    Docs Hibernate 4.1 - SessionFactoryImplementor.getConnectionProvider()

    【讨论】:

    • 导致 ClassCastException 的除外
    【解决方案2】:

    正如 Allinger Medeiros 所说,ConnectionProvider 在 Hibernate 4 中已被弃用,在 Hibernate 5 中不可用。 然而,正如 Gwaptiva 指出的那样,他的解决方案会导致 ClassCastException。

    这对我有用:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-06
      • 1970-01-01
      • 2011-12-28
      • 2019-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多