Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle jdbc.queryForObject if it doesn't return a row

I would like to know how to properly use jdbc in my case.

The saveLinkHistory column is a bit(1) type in mysql.

public boolean getIsSavedLinkHistory(String name) {
        String sql = "select saveLinkHistory from users where name = ?";
        Boolean isTracked = jdbcTemplateObject.queryForObject(sql, new Object[] { name }, Boolean.class);
        return isTracked;
}

The query worked well until I got an error of Incorrect result size: expected 1, actual 0 because sometimes the name didn't exist, the queryForObject method expects that I ALWAYS get 1 row as a result.

How can I handle this case, just throw an exception that says "name" doesn't exist ? and by the way, is Boolean ok here ? because I didn't see such code before.

like image 290
Oleg Avatar asked Dec 19 '22 08:12

Oleg


1 Answers

Try this:

return DataAccessUtils.singleResult(jdbcTemplate.query(sql, new SingleColumnRowMapper<Boolean>(), param1, param2));
like image 121
Ariel Avatar answered Jan 31 '23 02:01

Ariel