Jdbctemplate query for string: EmptyResultDataAccessException: Incorrect result size: expected 1, actual 0

前端 未结 17 1222
执笔经年
执笔经年 2020-11-29 16:22

I am using Jdbctemplate to retrieve a single String value from the db. Here is my method.

    public String test() {
        String cert=null;
        Strin         


        
17条回答
  •  执笔经年
    2020-11-29 17:02

    Since returning a null when there is no data is something I want to do often when using queryForObject I have found it useful to extend JdbcTemplate and add a queryForNullableObject method similar to below.

    public class JdbcTemplateExtended extends JdbcTemplate {
    
        public JdbcTemplateExtended(DataSource datasource){
            super(datasource);
        }
    
        public  T queryForNullableObject(String sql, RowMapper rowMapper) throws DataAccessException {
            List results = query(sql, rowMapper);
    
            if (results == null || results.isEmpty()) {
                return null;
            }
            else if (results.size() > 1) {
                throw new IncorrectResultSizeDataAccessException(1, results.size());
            }
            else{
                return results.iterator().next();
            }
        }
    
        public  T queryForNullableObject(String sql, Class requiredType) throws DataAccessException {
            return queryForObject(sql, getSingleColumnRowMapper(requiredType));
        }
    
    }
    

    You can now use this in your code the same way you used queryForObject

    String result = queryForNullableObject(queryString, String.class);
    

    I would be interested to know if anyone else thinks this is a good idea?

提交回复
热议问题