使用jdbcTemplate的queryForMap方法查询的时候报以下错误:
org.springframework.dao.EmptyResultDataAccessException: Incorrect result size: expected1, actual 0,也就是说结果不能返回空值。看下面的代码例子,执行代码时就会出现上述的异常。
@Service
@Transactional
public class OverflowCommonServiceImpl implements OverflowCommonService
{
@Autowired
private JdbcTemplate jdbcTemplate;
public Map<String, Object> findOneForJdbc(String tableName,String fieldName, String id) {
StringBuffer sqlBuffer = new StringBuffer();
sqlBuffer.append("select * from ").append(tableName);
sqlBuffer.append(" where "+fieldName+"='").append(id).append("'");
return jdbcTemplate.queryForMap(sqlBuffer.toString());
}
}
解决方法:
捕捉异常即可,正确代码如下所示:
@Service
@Transactional
public class OverflowCommonServiceImpl implements OverflowCommonService
{
@Autowired
private JdbcTemplate jdbcTemplate;
public Map<String, Object> findOneForJdbc(String tableName,String fieldName, String id) {
StringBuffer sqlBuffer = new StringBuffer();
sqlBuffer.append("select * from ").append(tableName);
sqlBuffer.append(" where "+fieldName+"='").append(id).append("'");
try {
return jdbcTemplate.queryForMap(sqlBuffer.toString());
} catch (Exception e) {
return null;
}
}
}
本文地址: