2

@Spring: I wrote a Dao which find a id by another id. when it get the data its fine but when not found shows an exception such like this.

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

Here is the dao:

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;
        }
    }

1 Answers1

6

I don't see any problem with your code. You are asking JdbcTemplate to find a single row for you, however, the merchantId you are querying does not exist probably on the database. The queryForObject() requires only one row to be returned. Best practice would be to append 'LIMIT 1' to your query, so that not more than one row is returned.

Please read this documentation reference. Notice the Throws section there, where IncorrectResultSizeDataAccessException is thrown in case the resultset contains 0 or more than 1 rows.

Additionally, read this post here.

Community
  • 1
  • 1
sbsatter
  • 591
  • 3
  • 22