如何在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
相关产品推荐
相关产品推荐

