【问题标题】:Apache DBCP Connection Pool error with Hibernate: Initial SessionFactory creation failedHibernate 的 Apache DBCP 连接池错误:初始 SessionFactory 创建失败
【发布时间】:2015-01-06 17:19:34
【问题描述】:

Hibernate 的 Apache DBCP 连接池错误:初始 SessionFactory 创建失败。不知道有什么问题?请参阅第 17 和 158 行的注释。

> Initial SessionFactory creation failed.java.lang.NullPointerException
> java.lang.NullPointerException    at
> ru.user.util.DBCPConnectionProvider.getConnection(DBCPConnectionProvider.java:158)
>   at
> org.hibernate.engine.jdbc.internal.JdbcServicesImpl$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcServicesImpl.java:279)
>   at
> org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:124)
>   at
> org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:89)
>   at
> org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:206)
>   at
> org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:178)
>   at
> org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1885)
>   at
> org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1843)
>   at
> ru.user.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:17)
>   at ru.user.util.HibernateUtil.<clinit>(HibernateUtil.java:9)    at
> ru.user.action.LoginAction.execute(LoginAction.java:43)


private static SessionFactory buildSessionFactory() {
        try {   
            // Create the SessionFactory from hibernate.cfg.xml
            Configuration configuration = new Configuration().configure();
            StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().
                    applySettings(configuration.getProperties());
            return configuration.buildSessionFactory(builder.build());
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            ex.printStackTrace();
            throw new ExceptionInInitializerError(ex);
        }
    }

在 hibernate.cfg.xml 中

<property name="hibernate.connection.provider_class">
    ru.user.util.DBCPConnectionProvider
</property>

和

private static SessionFactory buildSessionFactory() {
        try {   
            // Create the SessionFactory from hibernate.cfg.xml
            Configuration configuration = new Configuration().configure();
            StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().
                    applySettings(configuration.getProperties());
            return configuration.buildSessionFactory(builder.build()); //////// line 17
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            ex.printStackTrace();
            throw new ExceptionInInitializerError(ex);
        }
    }



public class DBCPConnectionProvider implements ConnectionProvider {

    private static final long serialVersionUID = 1L;

    private static final Logger log = LoggerFactory
            .getLogger(DBCPConnectionProvider.class);
    private static final String PREFIX = "hibernate.dbcp.";
    private BasicDataSource ds;

    // Old Environment property for backward-compatibility (property removed in
    // Hibernate3)
    private static final String DBCP_PS_MAXACTIVE = "hibernate.dbcp.ps.maxActive";

    // Property doesn't exists in Hibernate2
    private static final String AUTOCOMMIT = "hibernate.connection.autocommit";

    public void configure(Properties props) throws HibernateException {
        try {
            log.debug("Configure DBCPConnectionProvider");

            // DBCP properties used to create the BasicDataSource
            Properties dbcpProperties = new Properties();

            // DriverClass & url
            String jdbcDriverClass = props.getProperty(Environment.DRIVER);
            String jdbcUrl = props.getProperty(Environment.URL);
            dbcpProperties.put("driverClassName", jdbcDriverClass);
            dbcpProperties.put("url", jdbcUrl);

            // Username / password
            String username = props.getProperty(Environment.USER);
            String password = props.getProperty(Environment.PASS);
            dbcpProperties.put("username", username);
            dbcpProperties.put("password", password);

            // Isolation level
            String isolationLevel = props.getProperty(Environment.ISOLATION);
            if ((isolationLevel != null)
                    && (isolationLevel.trim().length() > 0)) {
                dbcpProperties.put("defaultTransactionIsolation",
                        isolationLevel);
            }

            // Turn off autocommit (unless autocommit property is set)
            String autocommit = props.getProperty(AUTOCOMMIT);
            if ((autocommit != null) && (autocommit.trim().length() > 0)) {
                dbcpProperties.put("defaultAutoCommit", autocommit);
            } else {
                dbcpProperties.put("defaultAutoCommit",
                        String.valueOf(Boolean.FALSE));
            }

            // Pool size
            String poolSize = props.getProperty(Environment.POOL_SIZE);
            if ((poolSize != null) && (poolSize.trim().length() > 0)
                    && (Integer.parseInt(poolSize) > 0)) {
                dbcpProperties.put("maxActive", poolSize);
            }

            // Copy all "driver" properties into "connectionProperties"
            Properties driverProps = ConnectionProviderInitiator
                    .getConnectionProperties(props);
            if (driverProps.size() > 0) {
                StringBuffer connectionProperties = new StringBuffer();
                for (Iterator<?> iter = driverProps.entrySet().iterator(); iter
                        .hasNext();) {
                    @SuppressWarnings("rawtypes")
                    Map.Entry entry = (Map.Entry) iter.next();
                    String key = (String) entry.getKey();
                    String value = (String) entry.getValue();
                    connectionProperties.append(key).append('=').append(value);
                    if (iter.hasNext()) {
                        connectionProperties.append(';');
                    }
                }
                dbcpProperties.put("connectionProperties",
                        connectionProperties.toString());
            }

            // Copy all DBCP properties removing the prefix
            for (Iterator<?> iter = props.entrySet().iterator(); iter.hasNext();) {
                @SuppressWarnings("rawtypes")
                Map.Entry entry = (Map.Entry) iter.next();
                String key = (String) entry.getKey();
                if (key.startsWith(PREFIX)) {
                    String property = key.substring(PREFIX.length());
                    String value = (String) entry.getValue();
                    dbcpProperties.put(property, value);
                }
            }

            // Backward-compatibility
            if (props.getProperty(DBCP_PS_MAXACTIVE) != null) {
                dbcpProperties.put("poolPreparedStatements",
                        String.valueOf(Boolean.TRUE));
                dbcpProperties.put("maxOpenPreparedStatements",
                        props.getProperty(DBCP_PS_MAXACTIVE));
            }

            // Some debug info
            if (log.isDebugEnabled()) {
                log.debug("Creating a DBCP BasicDataSource with the following DBCP factory properties:");
                StringWriter sw = new StringWriter();
                dbcpProperties.list(new PrintWriter(sw, true));
                log.debug(sw.toString());
            }

            // Let the factory create the pool
            ds = (BasicDataSource) BasicDataSourceFactory
                    .createDataSource(dbcpProperties);

            // The BasicDataSource has lazy initialization
            // borrowing a connection will start the DataSource
            // and make sure it is configured correctly.
            Connection conn = ds.getConnection();
            conn.close();

            // Log pool statistics before continuing.
            logStatistics();
        } catch (Exception e) {
            String message = "Could not create a DBCP pool";
            log.error(message, e);
            if (ds != null) {
                try {
                    ds.close();
                } catch (Exception e2) {
                    // ignore
                }
                ds = null;
            }
            throw new HibernateException(message, e);
        }
        log.debug("Configure DBCPConnectionProvider complete");
    }

    public Connection getConnection() throws SQLException {
        Connection conn = null;
        try {
            conn = ds.getConnection();  //////// line 158
        } finally {
            logStatistics();
        }
        return conn;
    }

    public void closeConnection(Connection conn) throws SQLException {
        try {
            conn.close();
        } finally {
            logStatistics();
        }
    }

    public void close() throws HibernateException {
        log.debug("Close DBCPConnectionProvider");
        logStatistics();
        try {
            if (ds != null) {
                ds.close();
                ds = null;
            } else {
                log.warn("Cannot close DBCP pool (not initialized)");
            }
        } catch (Exception e) {
            throw new HibernateException("Could not close DBCP pool", e);
        }
        log.debug("Close DBCPConnectionProvider complete");
    }

    protected void logStatistics() {
        if (log.isInfoEnabled()) {
            // log.info("active: " + ds.getNumActive() + " (max: " +
            // ds.getMaxTotal() + ") "
            // + "idle: " + ds.getNumIdle() + "(max: " + ds.getMaxIdle() + ")");
        }
    }

    public boolean supportsAggressiveRelease() {
        return false;
    }

    @Override
    public boolean isUnwrappableAs(
            @SuppressWarnings("rawtypes") Class unwrapType) {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public <T> T unwrap(Class<T> unwrapType) {
        // TODO Auto-generated method stub
        return null;
    }
}

请查看代码中的 cmets 以及堆栈跟踪中引用的行号。那么它有什么问题呢?我使用 dbcp2 池。

【问题讨论】:

  • 检查您的数据源对象,问题与 BasicDataSource 对象有关,该对象未在方法 configure 中填充
  • DBCPConnectionProvider 的 configure() 方法在哪里被调用?我没看到。你看到日志条目了吗?
  • @RE350 是的,ds 对象为空,原因是:DBCPConnectionProvider 中的 configue() 方法未启动,必须​​初始化 ds 对象。我不确定该方法必须由休眠运行还是必须显式运行?
  • DBCPConnectionProvider 中的configure() 方法不是ConnectionProvider 接口的一部分,所以我认为你需要显式地运行它。
  • @DavidLevesque 你能看到这个mkyong.com/hibernate/… 的例子吗?这正是我尝试做的,但我没有找到 configure 方法开始的地方。

标签: java hibernate jdbc apache-commons-dbcp


【解决方案1】:

您所指的示例是针对旧版本的 Hibernate。它不适用于 Hibernate 4+,因为接口 org.hibernate.connection.ConnectionProvider 不再存在。

我认为新方法是创建一个org.apache.commons.dbcp.BasicDataSource 的实例作为您的数据源。您可以找到一个示例 here(向下滚动到“Apache Commons DBCP 示例”)。

也可以通过Hibernate配置来实现,如this answer所示。

【讨论】:

    猜你喜欢
    • 2015-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-25
    • 2013-05-28
    • 2015-03-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多