01: // $Id: ResultSetIterator.java 12 2007-08-29 05:23:13Z jcamaia $
02:
03: package net.sf.persist;
04:
05: import java.sql.ResultSet;
06: import java.sql.SQLException;
07: import java.util.Iterator;
08:
09: /**
10: * Iterator backed by a ResultSet.
11: */
12: public final class ResultSetIterator implements Iterator {
13:
14: public static final int TYPE_OBJECT = 1;
15: public static final int TYPE_MAP = 2;
16:
17: private final ResultSet resultSet;
18: private final Persist persist;
19: private final Class objectClass;
20: private final int type;
21: private boolean hasNext = false;
22:
23: public ResultSetIterator(final Persist persist,
24: final Class objectClass, final ResultSet resultSet,
25: final int type) {
26:
27: if (type != TYPE_OBJECT && type != TYPE_MAP) {
28: throw new RuntimeSQLException(
29: "Invalid ResultSetIterator type: " + type);
30: }
31:
32: this .persist = persist;
33: this .objectClass = objectClass;
34: this .resultSet = resultSet;
35: this .type = type;
36:
37: try {
38: hasNext = resultSet.next();
39: } catch (SQLException e) {
40: throw new RuntimeSQLException(e);
41: }
42: }
43:
44: public boolean hasNext() {
45: return hasNext;
46: }
47:
48: public Object next() {
49: try {
50: final Object ret;
51: if (type == TYPE_OBJECT) {
52: ret = persist.loadObject(objectClass, resultSet);
53: } else if (type == TYPE_MAP) {
54: ret = Persist.loadMap(resultSet);
55: } else {
56: ret = null;
57: }
58:
59: hasNext = resultSet.next();
60: return ret;
61: } catch (SQLException e) {
62: throw new RuntimeSQLException(e);
63: }
64: }
65:
66: public void remove() {
67: try {
68: this .resultSet.deleteRow();
69: } catch (SQLException e) {
70: throw new RuntimeSQLException(e);
71: }
72: }
73:
74: }
|