JDBCTemplate find if row exists

You may use something like this:

String sql = "SELECT count(*) FROM MyTable WHERE Param = ?";
boolean exists = false;
int count = getJdbcTemplate().queryForObject(sql, new Object[] { "paramValue" }, Integer.class);
exists = count > 0;

Angelo


Using query methods from JdbcTemplate is way better for this situation, because they allow zero rows to be returned (no EmptyResultDataAccessException):

boolean hasRecord =
  jdbcTemplate
    .query("select 1 from MyTable where Param = ?",
      new Object[] { myParam },
      (ResultSet rs) -> {
        if (rs.next()) {
          return true;
        }
        return false;
      }
    );

If database supports exists (like Postgres for example), it is better to use it:

String query = "SELECT EXISTS(SELECT * FROM table_name WHERE ...)";
boolean exists = jdbcTemplate.queryForObject(query, params, Boolean.class);

Fastest check if row exists in PostgreSQL