首页 > 解决方案 > DAO 实现方法上的空指针异常

问题描述

我试图从数据库中获取值。当我运行 DAO 方法时,我得到 java.lang.NullpointerException。有人可以在这里帮助我下面的代码有什么问题吗?欢迎参考文章。

这是我的 DAO 课程。

package com.shiva.DAO;

import java.util.ArrayList;
import java.util.List;

import com.shiva.entity.Accountdetails;

public interface AccountDAO {
    public Accountdetails getActdetails();

    public List<String> getonlyto();

}

下面的类是模型类。名称、地址、帐户 ID 由 getter 和 setter 定义。

package com.shiva.entity;

public class Accountdetails {
    private String address;
    private int accountid;
    private String first_name;
    //Getters and Setters
}

下面的类是使用 @Repository 注释的 AccountDAOImpl 类。

package com.shiva.DAO;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.shiva.entity.AccountDetailMapper;
import com.shiva.entity.Accountdetails;

@Repository("accountDAO")
public class AccountDAOImpl implements AccountDAO {
    private static final Logger logger = LoggerFactory.getLogger(AccountDAOImpl.class.getName());

    @Autowired
    private JdbcTemplate jdbctemplate;

    public AccountDAOImpl() {

    }

    public AccountDAOImpl(JdbcTemplate jdbctemplate) throws SQLException {
        this.jdbctemplate = jdbctemplate;
    }

    @Override
    public List<String> getonlyto() {
        // TODO Auto-generated method stub

        String sql = ("select first_name from public.accountlist");
        getolto = this.jdbctemplate.queryForList(sql, String.class);

        return getolto;

    }

}

在主类中测试 getonlyto 方法。

package com.shiva.learn;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.shiva.DAO.AccountDAO;
import com.shiva.DAO.AccountDAOImpl;
import com.shiva.entity.Accountdetails;

public class Testrun {

    // private static Test one=new Test();
    private static final Logger logger = LoggerFactory.getLogger(Testrun.class);

    public static void main(String args[])

    {
        AccountDAOImpl accountimpl = new AccountDAOImpl();

        for (String daolist : accountimpl.getonlyto()) {
            System.out.println(daolist);

        }

    }

}

错误详情 :

Exception in thread "main" java.lang.NullPointerException
    at com.shiva.DAO.AccountDAOImpl.getonlyto(AccountDAOImpl.java:68)
    at com.shiva.learn.Testrun.main(Testrun.java:23)

标签: javaspringnullpointerexceptionjdbctemplate

解决方案


推荐阅读