javaapache-commons-dbutils

How do I query for a Set<MyObject> using DBUtils?


Looking over the DBUtils API docs, I cannot see if it's possible to query for a Set.

Which implementation of ResultSetHandler i should use for query Set of objects?


Solution

  • I don't think there is a default implementation for Set. You can create a generalized handler for Set as shown below.

    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;
        }
    }
    

    One down side is that toBean method tries to find ResulSet Column-Bean Property mapping for every row in the ResultSet where as toBeanListmethod(used by BeanListHandler) find this mapping only once per list.

    There is a BeanMapHandler which returns HashMap and it internally uses toBean method and hence I think for Sets/Maps we have to rely on toBean method or write a custom RowProcessor.