Apache DBCP Connection Pool грешка с Hibernate: Неуспешно първоначално създаване на SessionFactory

Apache DBCP Connection Pool грешка с Hibernate: Неуспешно първоначално създаване на 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;
    }
}

Моля, вижте коментарите в кода с номера на редове, посочени в трасирането на стека. И така, какво не е наред с това? Използвам dbcp2 pool.


person andy007    schedule 06.01.2015    source източник
comment
проверете вашия обект на източник на данни, проблемът е свързан с обект BasicDataSource, който не се попълва в configure на метода   -  person dReAmEr    schedule 06.01.2015
comment
Къде се извиква метод configure() на DBCPConnectionProvider? не го виждам Виждате ли записите в дневника?   -  person David Levesque    schedule 06.01.2015
comment
@RE350 да, ds обектът е null и причината за това: методът configue() в DBCPConnectionProvider не е стартиран, където ds обектът трябва да бъде инициализиран. Не съм сигурен дали този метод трябва да работи чрез хибернация или трябва да го стартирам изрично?   -  person andy007    schedule 06.01.2015
comment
Методът configure() в DBCPConnectionProvider не е част от интерфейса на ConnectionProvider, така че мисля, че трябва да го изпълните изрично.   -  person David Levesque    schedule 06.01.2015
comment
@DavidLevesque можеш ли да видиш този mkyong.com /hibernate/ пример? точно това се опитвам да направя и не намерих там къде е започнал методът за конфигуриране.   -  person andy007    schedule 06.01.2015
comment
Какво е пълното име на ConnectionProvider във вашите импортирания?   -  person David Levesque    schedule 06.01.2015
comment
@DavidLevesque org.hibernate.engine.jdbc.connections.spi.ConnectionProvider   -  person andy007    schedule 06.01.2015
comment
@DavidLevesque също реда Properties driverProps = ConnectionProviderInitiator.getConnectionProperties(props); се различава от оригиналния пример   -  person andy007    schedule 06.01.2015
comment
Не е същото като в примера. Този пример е за по-стара версия на Hibernate. Коя версия използвате?   -  person David Levesque    schedule 06.01.2015
comment
@DavidLevesque Hibernate 4.3.0 Final   -  person andy007    schedule 06.01.2015


Отговори (1)


Примерът, който имате предвид, е за по-стара версия на Hibernate. Няма да работи с Hibernate 4+, защото интерфейсът org.hibernate.connection.ConnectionProvider вече не съществува.

Мисля, че новият подход е да създадете екземпляр на org.apache.commons.dbcp.BasicDataSource като ваш DataSource. Можете да намерите пример тук (превъртете надолу до „Пример за Apache Commons DBCP“).

Възможно е също да го направите чрез конфигурацията на Hibernate, както е показано в този отговор.

person David Levesque    schedule 06.01.2015