I am using Jdbctemplate to retrieve a single String value from the db. Here is my method.
public String test() {
String cert=null;
Strin
That's not a good solution because you're relying on exceptions for control flow. In your solution it's normal to get exceptions, it's normal to have them in the log.
public String test() {
String sql = "select ID_NMB_SRZ from codb_owner.TR_LTM_SLS_RTN where id_str_rt = '999' and ID_NMB_SRZ = '60230009999999'";
List<String> certs = jdbc.queryForList(sql, String.class);
if (certs.isEmpty()) {
return null;
} else {
return certs.get(0);
}
}
Since getJdbcTemplate().queryForMap expects minimum size of one but when it returns null it shows EmptyResultDataAccesso fix dis when can use below logic
Map<String, String> loginMap =null;
try{
loginMap = getJdbcTemplate().queryForMap(sql, new Object[] {CustomerLogInInfo.getCustLogInEmail()});
}
catch(EmptyResultDataAccessException ex){
System.out.println("Exception.......");
loginMap =null;
}
if(loginMap==null || loginMap.isEmpty()){
return null;
}
else{
return loginMap;
}
For Byron, you can try this..
public String test(){
String sql = "select ID_NMB_SRZ from codb_owner.TR_LTM_SLS_RTN
where id_str_rt = '999' and ID_NMB_SRZ = '60230009999999'";
List<String> li = jdbcTemplate.queryForList(sql,String.class);
return li.get(0).toString();
}
In JdbcTemplate , queryForInt
, queryForLong
, queryForObject
all such methods expects that executed query will return one and only one row. If you get no rows or more than one row that will result in IncorrectResultSizeDataAccessException
. Now the correct way is not to catch this exception or EmptyResultDataAccessException
, but make sure the query you are using should return only one row. If at all it is not possible then use query
method instead.
List<String> strLst = getJdbcTemplate().query(sql,new RowMapper {
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs.getString(1);
}
});
if ( strLst.isEmpty() ){
return null;
}else if ( strLst.size() == 1 ) { // list contains exactly 1 element
return strLst.get(0);
}else{ // list contains more than 1 elements
//your wish, you can either throw the exception or return 1st element.
}
IMHO returning a null
is a bad solution because now you have the problem of sending and interpreting it at the (likely) front end client.
I had the same error and I solved it by simply returning a List<FooObject>
.
I used JDBCTemplate.query()
.
At the front end (Angular web client), I simply examine the list and if it is empty (of zero length), treat it as no records found.