简体   繁体   中英

jdbcTemplate.queryForObject gives java.lang.NullPointerException

I am trying to query for an object from the database but I keep on getting a java.lang.NullPointerException error even when the data is present in the database. How do I fix this?

UserLogin POJO Class

public class UserLogin {

    private int usercode;
    private String userid;
    private String userpassword;
    private String userrole;
    private String username;
    private boolean useraccess;

    public UserLogin() {
    }

    public UserLogin(int usercode, String userid, String userpassword, String userrole, String username, boolean useraccess) {
        this.usercode = usercode;
        this.userid = userid;
        this.userpassword = userpassword;
        this.userrole = userrole;
        this.username = username;
        this.useraccess = useraccess;
    }
//getters and setters...

DAO Class:

@Transactional
@Repository("daoUser")
public class DaoUser{

    private JdbcTemplate jdbcTemplate;

    public UserLogin getUserlogin(final String userid) {
        UserLogin user = new UserLogin();
        try {
            String sql = "SELECT usercode, userid, userpassword, userrole, username, useraccess FROM myschema.userlogin WHERE userid=?";
            Object[] criteria = { userid };
            user = jdbcTemplate.queryForObject(sql, BeanPropertyRowMapper.newInstance(UserLogin.class), criteria);
            
        } catch (Exception e) {
            System.out.println("Error in DaoUser.getUserlogin(final String userid) : " + e);
        }
        return user;
    }
}

The Error:

Error in DaoUserManagement.getUserlogin(final String userid) : java.lang.NullPointerException

The Data I'm trying to fetch:

usercode    userid  userpassword    userrole    username    useraccess

3           userA   userpassword    A           username    true

Where do you initialise jdbcTemplate object? So the actual numm pointer exception is at this object.

Use @Autowired or do the constructor injection.

@Autowired private JdbcTemplate jdbcTemplate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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