0

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?

Talenel
  • 422
  • 2
  • 6
  • 25
Roberto Petrilli
  • 711
  • 1
  • 8
  • 22
  • Does this answer your question? [How to get Map data using JDBCTemplate.queryForMap](https://stackoverflow.com/questions/10029785/how-to-get-map-data-using-jdbctemplate-queryformap) – Ryuzaki L Feb 14 '22 at 03:34
  • "How to get Map data using JDBCTemplate.queryForMap" does not answer my question. My problem is not to populate a map out of a resultset but to have a callback on each record I can use for any computation. The answer from pete below is, in my opinion, a cleaner solution. – Roberto Petrilli Feb 14 '22 at 09:41

2 Answers2

0
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);
0

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!

pete_bc
  • 76
  • 4