You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Jdbi的useTransaction Lambda表达式中更简便地从数据库获取值列表?

如何在Jdbi的useTransaction Lambda表达式中更简便地从数据库获取值列表?

哈哈,太懂这种用AtomicReference绕圈子的烦躁了!其实Jdbi本身就提供了更简洁的方案,完全不用这么麻烦~

你之前用的useTransaction方法是无返回值的,所以才不得不借助外部容器来传递结果。Jdbi还有个兄弟方法withTransaction,它专门支持在事务Lambda里返回值,完美解决你的问题:

private List<Integer> getIds(Jdbi jdbi) {
    return jdbi.withTransaction(handle -> {
        return handle.createQuery("select distinct id from table_x where status = 12")
                     .mapTo(Integer.class)
                     .list();
    });
}

是不是清爽多了?withTransaction会帮你处理事务的提交和回滚逻辑,同时直接把Lambda里返回的列表传递出来,完全不需要AtomicReference或者其他包装类。

如果你的代码风格更偏爱简洁,还可以把Lambda进一步简化:

private List<Integer> getIds(Jdbi jdbi) {
    return jdbi.withTransaction(handle -> 
        handle.createQuery("select distinct id from table_x where status = 12")
              .mapTo(Integer.class)
              .list()
    );
}

另外提一句:如果这个查询是只读操作,其实你甚至不需要开启事务,直接用withHandle方法会更轻量:

private List<Integer> getIds(Jdbi jdbi) {
    return jdbi.withHandle(handle -> 
        handle.createQuery("select distinct id from table_x where status = 12")
              .mapTo(Integer.class)
              .list()
    );
}

这样写出来的代码不仅简洁,还完全符合Jdbi的设计初衷,再也不用为了传递结果而搞额外的容器啦~

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.08 09:04:36