How to Solve Namedparameterjdbctemplate.queryforobject() Return Error

Project scenario:

tip: briefly describe the project background here:
for example, project scenario: example: communicate with mobile app through Bluetooth chip (hc-05), and transmit a batch of sensor data every 5S (not very large)


Problem Description:

The following code will report an error if it can’t be found in the database, and it doesn’t work whether you judge it to be empty or judge the length.

@Override
public String queryUserNameByUserId(String userId) {
	String sql = "SELECT username FROM info WHERE userId= :userId";
	MapSqlParameterSource source = new MapSqlParameterSource();
	source.addValue("userId", userId);
	return namedParameterJdbcTemplate.queryForObject(sql, source, String.class);
}

Cause analysis:

Queryforobject(), try to operate when querying data that must exist in the database.

Solution:

1. Try catch is not recommended
2. Change to list and judge to be empty, as follows.

@Override
public List<String> queryUserNameByUserId(String userId) {	//Modify
	String sql = "SELECT username FROM info WHERE userId= :userId";
	MapSqlParameterSource source = new MapSqlParameterSource();
	source.addValue("userId", userId);
    return namedParameterJdbcTemplate.queryForList(sql, source, String.class);	//修改
}

Read More: