Announcement Announcement Module
No announcement yet.
Correct way to return a scalar value: SqlFunction NPE Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Correct way to return a scalar value: SqlFunction NPE


    What is the correct way to return a scalar int value that must be 0 if null?

    I would like to return the sum of a column in a table:
    SELECT SUM(units) unit_sum FROM table t where y = ?

    SqlFunction triggers a NPE if the result is empty:
    public int run(Object[] args) {
    		Integer i = (Integer) super.findObject(args);
    		return i.intValue();
    This code doesn't , but seems kind of redundant:
    MyQuery extends MappingSqlQuery {
    public int execute(int y) {
                Object result = DataAccessUtils.uniqueResult(execute(y));
                int retVal = 0;
                if (result != null) {
                    retVal = ((Integer)result).intValue();
                return retVal;
    protected Object mapRow(ResultSet rs, int rowNum) throws SQLException{
                return new Integer(rs.getInt("unit_sum"));
    Is there a better way to get the count from a database, and 0 if there is no rows? Should there be a new method in DataAccessUtils? Should SqlFunction be updated to return 0 on null (or new method)?

  • #2
    The easies way is to use the JdbcTemplate method queryForInt. It will act as if you were calling getInt() on a result set and return 0 if the value is null. If you need the null, then you could use queryForObject. Here is an example:
    		JdbcTemplate jt = new JdbcTemplate(dataSource);
    		int i = jt.queryForInt(sql);
    		Integer o = (Integer)jt.queryForObject(sql, Integer.class);
    • int i --> 0
      Integer o --> null


    • #3
      Thanks! That's exactly what I was looking for...

      Much appreciated - I knew I was using the API wrong/using the wrong API.