mercredi 9 décembre 2015

Handling Null Pointer Exception on the prepared statement

Using Spring JDBC template trying to persist a collection of POJO populated by parsing Electronic Data Interchange (EDI) documents. Some variables in the POJO would be empty as its being populated based on some complex logic.

jdbcTemplate.batchUpdate("INSERT INTO test_bxp("npi,......................, ?, ?, ?);", new BatchPreparedStatementSetter() {

    @Override
        public void setValues(PreparedStatement ps, int i){

            try{
                Bxp bxp = bxpList.get(i);
                ps.setString(1, bxp.getNpi());
                ps.setString(2, bxp.getProviderno());
                ps.setString(3, bxp.getTapeid());
                ps.setString(4, bxp.getFi());
                ps.setString(5, bxp.getName());
                ps.setDate(6, new Date(bxp.getAdddate().getTime()));
                ps.setDate(7, new Date(bxp.getFpe().getTime()));
                ps.setDate(8, new Date(bxp.getMcaldate().getTime()));
                ps.setString(9, bxp.getChktrace());
                ps.setString(10, bxp.getMcalprovno());
                ps.setFloat(11, bxp.getDeduct());
                ps.setFloat(12, bxp.getCoinsur());
                ps.setInt(13,bxp.getMcrchgs());
            }catch(SQLException e){
                LOG.error("Yay! something went wrong take a look",e);
            }
}

Here bxp.getChktrace(), bxp.getCoinsur() .. might be null.

To avoid NPE I could do something like below

    private Float deduct = 0.0F;

    public void setDeduct(Float deduct) {
       if(deduct != null)           
          this.deduct = deduct;
    }

Is there any better solution for this other setting it explicitly on setter methods or constructors, using reflection?





Aucun commentaire:

Enregistrer un commentaire