Definitely the first way is the best practice, because in the second way you are hitting the database twice where you should actually hit it only once. This can cause performance issues.
What you need to do is catch the exception EmptyResultDataAccessException
and then return null back. Spring JDBC templates throws back an EmptyResultDataAccessException exception if it doesn’t find the data in the database.
Your code should look like this.
try {
sql = "SELECT id FROM tableNmae WHERE column_name=""+ coulmn value+ """;
id= jdbcTemplate.queryForObject(sql, Long.class);
}
catch (EmptyResultDataAccessException e) {
if(log.isDebugEnabled()){
log.debug(e);
}
return null
}