0

Apache DBCP Connection Pool error with Hibernate: Initial SessionFactory creation failed. have no idea what is wrong with it? Please, see cooments to line numbers 17 and 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);
        }
    }

in hibernate.cfg.xml

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

and

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;
    }
}

Please see comments in code with line numbers referenced in stack trace. So what is wrong wit it? I use dbcp2 pool.

10
  • check your datasource object,the problem is related to BasicDataSource object,which is not getiing populated inside method configure Commented Jan 6, 2015 at 17:23
  • Where is method configure() of DBCPConnectionProvider getting called? I don't see it. Do you see the log entries? Commented Jan 6, 2015 at 17:46
  • @RE350 yes, ds object is null and the reason for that: configue() method in DBCPConnectionProvider not started where ds object must be initialized. I'm not shure is that method must run by hibernate or I must run it explicitely? Commented Jan 6, 2015 at 17:46
  • 1
    The configure() method in DBCPConnectionProvider is not part of the ConnectionProvider interface, so I think you need to run it explicitely. Commented Jan 6, 2015 at 17:48
  • @DavidLevesque could you see this mkyong.com/hibernate/… example? it is exactly I try to do and I did not find there where configure method started. Commented Jan 6, 2015 at 17:51

1 Answer 1

1

The example you are referring to is for an older version of Hibernate. It will not work with Hibernate 4+ because the interface org.hibernate.connection.ConnectionProvider no longer exists.

I think the new approach is to create an instance of org.apache.commons.dbcp.BasicDataSource as your DataSource. You can find an example here (scroll down to "Apache Commons DBCP Example").

It is also possible to do it through the Hibernate configuration, as shown in this answer.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.