我正在使用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));
}
}
}
}但是,我很快发现RowReducer不能与ResultIterator一起工作(我使用的是一个大型数据库,所以能够流式传输这些内容很重要),所以现在我又回到了实现RowMapper。我仍然想使用JDBI中内置的方便的BeanMapper,但是我不知道如何从我的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了?
发布于 2020-08-17 00:50:07
RowMapper<Bar> barMapper = BeanMapper.of(Bar.class)
Bar bar = barMapper.map(rs, ctx);
foo.addBar(bar);https://stackoverflow.com/questions/59830691
复制相似问题