0

This is my DAO code

@Autowired
    public void setDataSource(DataSource dataSource) {
    this.jdbcTemplate = new JdbcTemplate(dataSource);

    }
    public JSONObject getdata(UserBean userBean)
    {
        JSONObject jsonObject = new JSONObject();
        return this.jdbcTemplate.queryForObject("select username from customer", new RowMapper<JSONObject>() {

            @Override
            public JSONObject mapRow(ResultSet rs, int rowNum) throws SQLException 
            {
                jsonObject.put("username",rs.getString("username"));
                return jsonObject;
            }

        });

    }

Then this is my controller code

    @SuppressWarnings("unchecked")
    @RequestMapping(value="/doLogin")
    public ModelAndView doLogin(@ModelAttribute @Valid UserBean userBean,BindingResult result)
    {
        ModelAndView view = new ModelAndView("login");
        if(!result.hasFieldErrors())
        {
            if(!combatService.authenticateUser(userBean)) 
            {
                result.addError(new ObjectError("err", "Invalid Credentials"));

            } 
            else
                {
                 if(retrieveService.getdata(userBean) != null)
                 {
                     JSONObject responseArray=new JSONObject();
                     responseArray.put("usernames",retrieveService.getdata(userBean));
                     return new ModelAndView("welcomes", responseArray);
                }   
                }
        }
        return view;
        }

And this is error

Message Request processing failed; nested exception is org.springframework.dao.IncorrectResultSizeDataAccessException: Incorrect result size: expected 1, actual 10

Vignesh_E
  • 167
  • 2
  • 4
  • 15
  • ...and [this is the place](https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/jdbc/core/JdbcTemplate.html#queryForObject-java.lang.String-org.springframework.jdbc.core.RowMapper-) you are supposed to look at. – Jakub Ch. Oct 05 '18 at 11:54

1 Answers1

0

Your query does a straight up SELECT username FROM customer, meaning, this query returns ALL usernames. Presumably, there are currently 10 records in your database.

You need to run SELECT username FROM customer WHERE (something something).

You haven't pasted your UserBean code, but assuming it has a getUserId() method in it, you'd do something like: return this.jdbcTemplate.queryForObject("select username from customer WHERE userId = ?", new RowMapper<JSONObject>() { ... }, userBean.getUserId()). Note how there's a new parameter at the end, after your rowmapper, with the value for the question mark in your SQL query.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72