码上敲享录 > Spring框架常见问题详解分享 > org.springframework.dao.EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0

org.springframework.dao.EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0

上一章章节目录下一章 2018-02-01已有3817人阅读 评论(0)

使用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;

}

}

}


本文地址:



向大家推荐《Activiti工作流实战教程》:https://xiaozhuanlan.com/activiti
0

有建议,请留言!

  • *您的姓名:

  • *所在城市:

  • *您的联系电话:

    *您的QQ:

  • 咨询问题:

  • 提 交