从 RowMapper 中使用 BeanMapper?

Use BeanMapper from within a RowMapper?

我正在使用 JDBI 的 SQL 对象声明 API 来映射包含一对多关系的对象:

class Foo {
  private String id;
  private String name;
  private Set<Bar> bars = new HashSet<>();
}

class Bar {
  private String id;
}

最初看起来 RowReducer 比较理想:

@UseFreemarkerSqlLocator
class FooQuery {

  @SqlQuery
  @RegisterBeanMapper(value = Foo.class, prefix = "f")
  @RegisterBeanMapper(value = Bar.class, prefix = "b")
  @UseRowReducer(RowReducer.class)
  ResultIterator<Foo> queryAll();

  static class RowReducer implements LinkedHashMapRowReducer<String, Foo> {

    @Override
    public void accumulate(Map<String, Foo> map, RowView rowView) {
      final Foo foo = map.computeIfAbsent(rowView.getColumn("f_id", String.class),
          id -> rowView.getRow(Foo.class));
      if (rowView.getColumn("b_id", String.class) != null) {
        foo.addBar(rowView.getRow(Bar.class));
      }
    }
  }
}

但是我很快发现 RowReducers 不适用于 ResultIterators(我正在使用一个大型数据库,所以能够流式传输这些数据很重要)所以现在我'我改回执行 RowMapper。我仍然想使用 JDBI 中内置的便捷 BeanMappers,但我不知道如何从我的 RowMapper 实现中访问它们。

class FooRowMapper implements RowMapper<Foo> {
  private Foo foo = null;

  @Override
  public Foo map(ResultSet rs, StatementContext ctx) throws SQLException {
    String fooId = rs.getString("f_id");
    if (foo == null || !foo.id.equals(fooId)) {
      // ideally construct using JDBI's BeanMapper similar to how we can above
      // in the RowReducer!
      foo = ??? 
    }
    // same as above...
    Bar bar = ???
    foo.addBar(bar);

    return foo;
  }
}

是否可以在 RowMapper 中轻松使用 BeanMappers,这样我就不必手动构建 bean?

RowMapper<Bar> barMapper = BeanMapper.of(Bar.class)
Bar bar = barMapper.map(rs, ctx);
foo.addBar(bar);