Home > Software design >  Better way to use JdbcTemplate with Lamda RowMapper
Better way to use JdbcTemplate with Lamda RowMapper

Time:02-14

Often in time I use jdbcTemplate.query not to return a resultset but to access the DB and do some computations on each record selected. For example the code below works

    Map<String, Double> mAcc = new HashMap<>();
    sql = "select ar.id_codice_art, sum(ar.quantita) quantita\n"  
            "from accettazione a \n"  
            "inner join accettazione_riga ar on a.id_accettazione = ar.id_accettazione\n"  
            "where a.id_ordine = ? \n"  
            "group by ar.id_codice_art";
    jdbcTemplate.query(sql, (rs, i)->{
        mAcc.put(rs.getString("id_codice_art"), rs.getDouble("quantita"));
        return "";
    }, idOrdine);

but it's not clean especially when a return "" because it is required by RowMapper interface. At the same time I don't want to create a record or a class just to return a list and work on the list.

Is there a better way to do the same think using jdbcTemplate?

CodePudding user response:

You can try using the following code. Just create a new map, insert values in it and return it. and then you can copy values from that result map to your map.

 Map<String, Double> mAcc = new HashMap<>();
    sql = "select ar.id_codice_art, sum(ar.quantita) quantita\n"  
            "from accettazione a \n"  
            "inner join accettazione_riga ar on a.id_accettazione = ar.id_accettazione\n"  
            "where a.id_ordine = ? \n"  
            "group by ar.id_codice_art";
    Map<String,Double> = jdbcTemplate.query(sql, (rs)->{
    Map<String,Double> map = new HashMap<>();
        while(rs.next()){
        map.put(rs.getString("id_codice_art"), rs.getDouble("quantita"));
        }
        return map;
    }, idOrdine);

CodePudding user response:

I'm assuming that the idOrdine key is a Long.

Map<String, Double> mAcc = new HashMap<>();
PreparedStatementSetter pss = ps -> ps.setLong(1, idOrdine);
RowCallbackHandler rch = rs -> mAcc.put(rs.getString("id_codice_art"),
     rs.getDouble("quantita"));
jdbcTemplate.query(sql, pss, rch);

Of course, you can in-line those lambdas to avoid importing those two classes.

I just learned that in researching your answer, and now I'm going to rewrite a chunk of code I just wrote for work to use that method too!

  • Related