如何使用 DBUtils 查询 Set<MyObject>?
How do I query for a Set<MyObject> using DBUtils?
查看 DBUtils API 文档,我看不出是否可以查询集合。
我应该使用 ResultSetHandler 的哪个实现来查询对象集?
我认为 Set
没有默认实现。您可以为 Set
创建通用处理程序,如下所示。
public class SetHandler<T> implements ResultSetHandler<Set<T>> {
private final RowProcessor rp = new BasicRowProcessor();
private final Class<T> type;
public SetHandler(Class<T> type) {
this.type = type;
}
@Override
public Set<T> handle(ResultSet rs) throws SQLException {
Set<T> set = new HashSet<>();
while (rs.next()) {
set.add((T) this.rp.toBean(rs,type));
}
return set;
}
}
一个缺点是 toBean
方法试图为 ResultSet 中的每一行找到 ResulSet Column-Bean 属性 映射,其中 toBeanList
方法(由 BeanListHandler 使用)找到这个每个列表只映射一次。
有一个 BeanMapHandler
,其中 returns HashMap 并且它在内部使用 toBean
方法,因此我认为对于 Sets/Maps 我们必须依赖 toBean
方法或编写自定义 RowProcessor
.
查看 DBUtils API 文档,我看不出是否可以查询集合。
我应该使用 ResultSetHandler 的哪个实现来查询对象集?
我认为 Set
没有默认实现。您可以为 Set
创建通用处理程序,如下所示。
public class SetHandler<T> implements ResultSetHandler<Set<T>> {
private final RowProcessor rp = new BasicRowProcessor();
private final Class<T> type;
public SetHandler(Class<T> type) {
this.type = type;
}
@Override
public Set<T> handle(ResultSet rs) throws SQLException {
Set<T> set = new HashSet<>();
while (rs.next()) {
set.add((T) this.rp.toBean(rs,type));
}
return set;
}
}
一个缺点是 toBean
方法试图为 ResultSet 中的每一行找到 ResulSet Column-Bean 属性 映射,其中 toBeanList
方法(由 BeanListHandler 使用)找到这个每个列表只映射一次。
有一个 BeanMapHandler
,其中 returns HashMap 并且它在内部使用 toBean
方法,因此我认为对于 Sets/Maps 我们必须依赖 toBean
方法或编写自定义 RowProcessor
.