We've all written a DAO:
Connection con = ...; PreparedStatement ps = con.prepareStatement("select ..."); ResultSet rs = ps.executeQuery(); List<YourEntity> list = new ArrayList<YourEntity>(); while (rs.next()) { // extract individual column values YourEntity entity = new YourEntity(...); list.add(entity); } rs.close(); ps.close(); con.close(); return list;
Then, in the calling code, iterate over the list to do something useful with it.
Jason B's colleague took a different path.
He created a dedicated DAO for each and every query. In each he made all the variables static, along with some static variables to maintain state. Then in his high level routine, he did this:
YourEntity entity = null; while ((entity = dao.getNextRow()) != null) { // process entity }
And in the DAO:
private static Connection con; private static PreparedStatement ps; private static ResultSet rs; public YourEntity getNextRow() { if (rs == null) { con = ...; ps = con.prepareStatement("select ..."); rs = ps.executeQuery(); } if (! rs.next()) { rs.close(); ps.close(); con.close(); rs = null; ps = null; con = null; return null; } // extract all fields from rs YourEntity e = new YourEntity(...); return e; }
Of course, the static variables force you to only have one instance of the DAO, so it's useless for threaded situations.
Jason's colleague explained: "The data set is quite large; this way it won't try to load the whole thing at once. Instead, it will load one row at a time."
When Jason pointed out that this is not the way to control how much data the server sends back at once, his colleague countered: "But it's only reading one row at a time!"