简体   繁体   English

将 JdbcTemplate 与 Lambda RowMapper 结合使用的更好方法

[英]Better way to use JdbcTemplate with Lambda RowMapper

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.我经常及时使用 jdbcTemplate.query 不返回结果集,而是访问数据库并对每个选定的记录进行一些计算。 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.但它并不干净,尤其是当返回“”时,因为它是 RowMapper 接口所必需的。 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?有没有更好的方法来使用 jdbcTemplate 做同样的事情?

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

I'm assuming that the idOrdine key is a Long.我假设 idOrdine 键是 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.当然,您可以内联这些 lambda 以避免导入这两个类。

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!我刚刚在研究您的答案时了解到这一点,现在我将重写我刚刚为工作编写的一大块代码,以使用该方法!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM