当前位置: 首页 > 知识库问答 >
问题:

Java语言C3P0ConnectionProvider中的lang.NullPointerException。getConnection()

国盛
2023-03-14

在我的应用程序中,我得到了java。C3P0ConnectionProvider中的lang.NullPointerException。最新hibernate jar文件中的getConnection()方法

使用的Jar文件是

hibernate-core-4.3.0.Beta5.jar
hibernate-c3p0-4.3.0.Beta5.jar
hibernate-commons-annotations-4.0.4.Final.jar
hibernate-entitymanager-4.3.0.Beta5.jar
hibernate-jpa-2.0-api-1.0.0.Final.jar
slf4j-api-1.7.5.jar
slf4j-simple-1.7.5.jar
jta-1.1.jar
jboss-logging-3.1.3.GA.jar
javax.persistence-2.1.0.jar

下面是我的C3P0ConnectionProvider类代码

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.Properties;

import javax.sql.DataSource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.HibernateException;
import org.hibernate.cfg.Environment;
import org.hibernate.engine.jdbc.connections.internal.ConnectionProviderInitiator;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.internal.util.config.ConfigurationHelper;
import org.hibernate.internal.util.ReflectHelper;

import com.mchange.v2.c3p0.DataSources;

public class C3P0ConnectionProvider implements ConnectionProvider {



    private static final Log log = LogFactory.getLog(C3P0ConnectionProvider.class);


    private final static String C3P0_STYLE_MIN_POOL_SIZE = "c3p0.minPoolSize";
    private final static String C3P0_STYLE_MAX_POOL_SIZE = "c3p0.maxPoolSize";
    private final static String C3P0_STYLE_MAX_IDLE_TIME = "c3p0.maxIdleTime";
    private final static String C3P0_STYLE_MAX_STATEMENTS = "c3p0.maxStatements";
    private final static String C3P0_STYLE_ACQUIRE_INCREMENT = "c3p0.acquireIncrement";
    private final static String C3P0_STYLE_IDLE_CONNECTION_TEST_PERIOD = "c3p0.idleConnectionTestPeriod";

    private final static String C3P0_STYLE_INITIAL_POOL_SIZE = "c3p0.initialPoolSize";

    private DataSource ds;
    private Integer isolation;
    private boolean autocommit;

    /**
     * {@inheritDoc}
     */
    public Connection getConnection() throws SQLException {
        final Connection c = ds.getConnection();
        if (isolation != null) {
            c.setTransactionIsolation(isolation.intValue());
        }
        if (c.getAutoCommit() != autocommit) {
            c.setAutoCommit(autocommit);
        }
        return c;
    }

    /**
     * {@inheritDoc}
     */
    public void closeConnection(Connection conn) throws SQLException {
        conn.close();
    }

    /**
     * {@inheritDoc}
     */
    public void configure(Properties props) throws HibernateException {
        String jdbcDriverClass = props.getProperty(Environment.DRIVER);
        String jdbcUrl = props.getProperty(Environment.URL);
        Properties connectionProps = ConnectionProviderInitiator.getConnectionProperties(props);


        autocommit = ConfigurationHelper.getBoolean(Environment.AUTOCOMMIT, props);

        if (jdbcDriverClass == null) {
            log.warn("No JDBC Driver class was specified by property "
                    + Environment.DRIVER);
        } else {
            try {
                Class.forName(jdbcDriverClass);
            } catch (ClassNotFoundException cnfe) {
                try {
                    ReflectHelper.classForName(jdbcDriverClass);
                } catch (ClassNotFoundException e) {
                    String msg = "JDBC Driver class not found: "
                            + jdbcDriverClass;
                    log.fatal(msg, e);
                    throw new HibernateException(msg, e);
                }
            }
        }

        try {


            Integer minPoolSize = ConfigurationHelper.getInteger(
                    Environment.C3P0_MIN_SIZE, props);
            Integer maxPoolSize = ConfigurationHelper.getInteger(
                    Environment.C3P0_MAX_SIZE, props);
            Integer maxIdleTime = ConfigurationHelper.getInteger(
                    Environment.C3P0_TIMEOUT, props);
            Integer maxStatements = ConfigurationHelper.getInteger(
                    Environment.C3P0_MAX_STATEMENTS, props);
            Integer acquireIncrement = ConfigurationHelper.getInteger(
                    Environment.C3P0_ACQUIRE_INCREMENT, props);
            Integer idleTestPeriod = ConfigurationHelper.getInteger(
                    Environment.C3P0_IDLE_TEST_PERIOD, props);

            Properties c3props = new Properties();

            // turn hibernate.c3p0.* into c3p0.*, so c3p0
            // gets a chance to see all hibernate.c3p0.*
            for (Iterator<?> ii = props.keySet().iterator(); ii.hasNext();) {
                String key = (String) ii.next();
                if (key.startsWith("hibernate.c3p0.")) {
                    String newKey = key.substring(10);
                    if (props.containsKey(newKey)) {
                        warnPropertyConflict(key, newKey);
                    }
                    c3props.put(newKey, props.get(key));
                }
            }

            setOverwriteProperty(Environment.C3P0_MIN_SIZE,
                    C3P0_STYLE_MIN_POOL_SIZE, props, c3props, minPoolSize);
            setOverwriteProperty(Environment.C3P0_MAX_SIZE,
                    C3P0_STYLE_MAX_POOL_SIZE, props, c3props, maxPoolSize);
            setOverwriteProperty(Environment.C3P0_TIMEOUT,
                    C3P0_STYLE_MAX_IDLE_TIME, props, c3props, maxIdleTime);
            setOverwriteProperty(Environment.C3P0_MAX_STATEMENTS,
                    C3P0_STYLE_MAX_STATEMENTS, props, c3props, maxStatements);
            setOverwriteProperty(Environment.C3P0_ACQUIRE_INCREMENT,
                    C3P0_STYLE_ACQUIRE_INCREMENT, props, c3props,
                    acquireIncrement);
            setOverwriteProperty(Environment.C3P0_IDLE_TEST_PERIOD,
                    C3P0_STYLE_IDLE_CONNECTION_TEST_PERIOD, props, c3props,
                    idleTestPeriod);

            // revert to traditional hibernate behavior of setting
            // initialPoolSize to minPoolSize
            // unless otherwise specified with a c3p0.*-style parameter.
            Integer initialPoolSize = ConfigurationHelper.getInteger(
                    C3P0_STYLE_INITIAL_POOL_SIZE, props);
            if (initialPoolSize == null && minPoolSize != null) {
                c3props.put(C3P0_STYLE_INITIAL_POOL_SIZE, String.valueOf(
                        minPoolSize).trim());
            }

            /*
             * DataSource unpooled = DataSources.unpooledDataSource( jdbcUrl,
             * props.getProperty(Environment.USER),
             * props.getProperty(Environment.PASS) );
             */
            DataSource unpooled = DataSources.unpooledDataSource(jdbcUrl,
                    connectionProps);

            Properties allProps = (Properties) props.clone();
            allProps.putAll(c3props);

            ds = DataSources.pooledDataSource(unpooled, allProps);
        } catch (Exception e) {
            log.fatal("could not instantiate C3P0 connection pool", e);
            throw new HibernateException(
                    "Could not instantiate C3P0 connection pool", e);
        }

        String i = props.getProperty(Environment.ISOLATION);
        if (i == null) {
            isolation = null;
        } else {
            isolation = new Integer(i);
            log.info("JDBC isolation level: "
                    + Environment.isolationLevelToString(isolation.intValue()));
        }

    }

    /**
     * {@inheritDoc}
     */
    public void close() {
        try {
            DataSources.destroy(ds);
        } catch (SQLException sqle) {
            log.warn("could not destroy C3P0 connection pool", sqle);
        }
    }

    /**
     * {@inheritDoc}
     */
    public boolean supportsAggressiveRelease() {
        return false;
    }

    private void setOverwriteProperty(String hibernateStyleKey,
            String c3p0StyleKey, Properties hibp, Properties c3p, Integer value) {
        if (value != null) {
            c3p.put(c3p0StyleKey, String.valueOf(value).trim());
            if (hibp.getProperty(c3p0StyleKey) != null) {
                warnPropertyConflict(hibernateStyleKey, c3p0StyleKey);
            }
            String longC3p0StyleKey = "hibernate." + c3p0StyleKey;
            if (hibp.getProperty(longC3p0StyleKey) != null) {
                warnPropertyConflict(hibernateStyleKey, longC3p0StyleKey);
            }
        }
    }

    private void warnPropertyConflict(String hibernateStyle, String c3p0Style) {
        log.warn("Both hibernate-style property '" + hibernateStyle
                + "' and c3p0-style property '" + c3p0Style
                + "' have been set in hibernate.properties. "
                + "Hibernate-style property '" + hibernateStyle
                + "' will be used " + "and c3p0-style property '" + c3p0Style
                + "' will be ignored!");
    }

    /**
     * @return the ds
     */
    public DataSource getDs() {
        return ds;
    }

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

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


}

在冬眠中。cfg。xml,我已经配置了c3p0

<property name="hibernate.connection.provider_class">C3P0ConnectionProvider</property>
<property name="hibernate.c3p0.acquire_increment">1</property>
<property name="hibernate.c3p0.max_size">1000</property>
<property name="hibernate.c3p0.max_statements">100</property>
<property name="hibernate.c3p0.min_size">50</property>
<property name="hibernate.c3p0.timeout">20</property> 

获取java。ds中的lang.NullPointerException。方法public Connection getConnection()中的getConnection()行#43。

这是我的异常stacktrace

Caused by: java.lang.NullPointerException
    at C3P0ConnectionProvider.getConnection(C3P0ConnectionProvider.java:60)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcServicesImpl.java:284)
    at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:129)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:89)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:160)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:132)
    at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1881)
    at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1839)
    at HibernateUtil.getFactory(HibernateUtil.java:43)
    at HibernateUtil.openSession(HibernateUtil.java:64)
    at HibernateUtil.currentSession(HibernateUtil.java:56)
    at openSession(CacheDaoImpl.java:404)
    at loadCache(CacheDaoImpl.java:94)
    at init(CacheDaoImpl.java:90)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeCustomInitMethod(AbstractAutowireCapableBeanFactory.java:1414)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1375)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1335)

提前感谢。

共有1个答案

牟星火
2023-03-14

看起来您的变量ds为null。

您确定在getConnection()之前调用configure(Properties props)吗?因为存在变量ds的初始化。

 类似资料:
  • 我试图将一分钟内收到的所有消息对象存储到树映射中,并在一分钟后将其序列化,并将字节[]返回到另一个类,同时清除映射并开始存储下一分钟内收到的消息,等等。 为什么这段代码给我空指针异常突出int len=b.length;的另一个类,它被称为返回值? 即使进行了修改(即将返回放在else块中),它也不会将控件返回给调用类。此外,在else块内未打印SOP语句(添加时)。为什么?

  • NullPointerException且未连接适配器;每次我在GennMotion上测试此应用程序时,都会跳过布局。我读过与同一问题相关的其他问题,但没有任何帮助。 logcat 09-20 13:21:13.7384658-4658/com。实例基兰。detailapp E/AndroidRuntime:致命异常:主进程:com。实例基兰。detailapp,PID:4658 java。lan

  • 本文向大家介绍Java语言中的Kruskal算法,包括了Java语言中的Kruskal算法的使用技巧和注意事项,需要的朋友参考一下 Kruskal算法是一种贪婪算法,其工作原理如下: 1.它在图形中创建一组所有边。 2.虽然上述集合不是空的,并且并非所有顶点都被覆盖, 它从该组中删除最小重量边 它检查此边缘是形成一个循环还是仅连接2棵树。如果形成一个循环,则丢弃该边,否则将其添加到树中。 3.完成

  • 根据我所学到的,抽象是一个隐藏内部实现的概念。 在Java中,我们可以通过接口、抽象关键字(类/方法)以及方法来实现抽象。例如扫描器s=新扫描器(System.in);int x=s.nextint();这里我们不需要了解nextInt()方法的任何内容。所以我可以说这是抽象。 同样的事情也可以在C语言中用printf()实现 所以,如果即使在非OOP语言中也能实现抽象,那么为什么在基于OOP的语

  • 问题内容: 我正在尝试更好地理解它们之间的区别。我在网上找到了很多解释,但它们倾向于抽象的差异,而不是实际的含义。 我的大部分编程经验都来自CPython(动态的,解释的)和Java(静态的,编译的)。但是,我知道还有其他种类的解释和编译语言。除了可以从以编译语言编写的程序中分发可执行文件这一事实之外,每种类型是否有优点/缺点?通常,我听到人们争辩说解释语言可以交互使用,但是我相信编译语言也可以具

  • 我使用的是Eclipse Juno,当我在某个工作区上启动它时,会出现以下错误: 发生错误。有关更多详细信息,请参阅错误日志。 java.lang.空指针异常 从同一SVN存储库中签出的其他工作区运行良好。有人知道为什么会这样吗? 在工作区日志中,我得到以下异常: !进入org.eclipse.m2e.logback.appender4 0 2014-03-11 13:26:25.798!MESS