I would like to write a efficiency database fetching method with reture an iterator so that the actually database read is on dedmand, something like this:
public Iterator static read(Connection con, String policyId) throws SQLException, NotFoundException{ ResultSet rset = null; final PreparedStatement pstmt = con.prepareStatement(SQL_SELECT_POILCY); try{ pstmt.setString(1, policyId); rset = pstmt.executeQuery(); return new Iterator () { public boolean hasNext() { return rset.isLast(); } public Object next() { if(rset.next()) { return new withdrawDeduction(policyId, rset.getInt(1), new BigDecimal(rset.getDouble(2))); else throw new NoSuchElementException(); } public void remove() { throw new UnsupportedOperationException(); } protected void finalize() throws Throwable{ try{ SQLUtility.cleanup(rset); SQLUtility.cleanup(pstmt); } catch(Throwable t) {} super.finalize(); } }; } }
However, according to "Efficient java", we should not rely on finalize to free resource, any better approach?