【问题标题】:How to solve EmptyResultDataAccessException?如何解决 EmptyResultDataAccessException?
【发布时间】:2017-05-21 11:19:23
【问题描述】:

@Spring:我写了一个 Dao,它通过另一个 id 找到一个 id。当它得到数据时它很好但当没有找到时会显示这样的异常。

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

这是道:

public Integer getIdByMerchantId(Integer merchantId) {
        String query = "SELECT id FROM transaction_history WHERE merchant_id=? ";
        try {
            return serviceJdbcTemplate.queryForObject(query, new Object[]{merchantId}, Integer.class);

        } catch (EmptyResultDataAccessException e) {
            log.error("Following query execution failed: ");
            log.error(Utils.getLoggerFriendlyQuery(query), merchantId);
            log.error("{} failed for merchant id {}. Error: {}", query, merchantId, e.getLocalizedMessage());
            return null;
        }
    }

【问题讨论】:

标签: spring


【解决方案1】:

我认为您的代码没有任何问题。 您要求 JdbcTemplate 为您找到一行,但是,您正在查询的 MercerId 可能在数据库中不存在。 queryForObject() 只需要返回一行。最佳做法是将“LIMIT 1”附加到您的查询中,以便返回的行不超过一行。

请阅读此documentation reference。注意那里的 Throws 部分,如果结果集包含 0 行或多于 1 行,则会引发 IncorrectResultSizeDataAccessException。

此外,请在此处阅读post

【讨论】:

  • 感谢您的帮助....现在我明白了。我想,在记录器上显示错误时可能是个问题。
猜你喜欢
  • 1970-01-01
  • 2017-03-07
  • 2017-01-07
  • 2013-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-26
  • 2018-06-01
相关资源
最近更新 更多