简体   繁体   English

尝试访问数据库时导致NullPointerException

[英]NullPointerException resulting when attempting to access database

This is the method which is giving me the NullPointerException . 这是给我NullPointerException I have narrowed it down to the line which queries the database. 我将其范围缩小到查询数据库的行。

The code does not reach the second logger. 该代码未到达第二个记录器。 The exception is thrown before it prints out. 在异常输出之前将其抛出。

UPDATE: I just tested the jdbcTemplate and it is what is NULL. 更新:我刚刚测试了jdbcTemplate,它是NULL。

public boolean usernameVerificationProcessService(String string){
    HomeController.logger.info("In method usernameVerificationProcessService in UIDao.");
    HomeController.logger.info("Attention: " + string);
    boolean result = false;
    String sql = "select count(*) from users where username = ?";
    int count = this.jdbcTemplate.queryForObject(sql, new Object[]{string}, java.lang.Integer.class);
    HomeController.logger.info("Attention: " + count);
    if(count == 0) {
        result = true;
    }
    return result;
}

This is the config file description. 这是配置文件的描述。 I am using a BasicDataSource and MySQL. 我正在使用BasicDataSource和MySQL。

<beans:bean id="dataSource" destroy-method="close" class="org.apache.commons.dbcp.BasicDataSource">
    <beans:property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <beans:property name="url" value="jdbc:mysql://localhost:3306"/>
    <beans:property name="username" value="test"/>
    <beans:property name="password" value="test"/>
    <beans:property name="initialSize" value="2" />
    <beans:property name="maxActive" value="5" />
</beans:bean>

Do you forget to inject the jdbcTemplate into the object? 您是否忘记将jdbcTemplate注入对象?

public class DBaseAccess {
    private JdbcTemplate jdbcTemplate;
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
  .......
}

You must inject the jdbcTemplate to the object in your spring config file (applicationContext.xml) 您必须将jdbcTemplate注入到spring配置文件(applicationContext.xml)中的对象

 <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    <property name="dataSource" ref="dataSource" />
 </bean>
 <bean id="dBaseAccess" class="coc.taf.dbase.DBaseAccess">
    <property name="jdbcTemplate" ref="jdbcTemplate" />
 </bean>

You never check the string parameter for null . 您永远不会检查string参数是否为null I guess it fails with NPE. 我想NPE失败了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM