Java Iterator backed by a ResultSet

后端 未结 17 741
清歌不尽
清歌不尽 2020-12-13 06:51

I\'ve got a class that implements Iterator with a ResultSet as a data member. Essentially the class looks like this:

public class A implements Iterator{
            


        
17条回答
  •  青春惊慌失措
    2020-12-13 07:30

    I agree with BalusC. Allowing an Iterator to escape from your DAO method is going to make it difficult to close any Connection resources. You will be forced to know about the connection lifecycle outside of your DAO, which leads to cumbersome code and potential connection leaks.

    However, one choice that I've used is to pass a Function or Procedure type into the DAO method. Basically, pass in some sort of callback interface that will take each row in your result set.

    For example, maybe something like this:

    public class MyDao {
    
        public void iterateResults(Procedure proc, Object... params)
               throws Exception {
    
            Connection c = getConnection();
            try {
                Statement s = c.createStatement(query);
                ResultSet rs = s.executeQuery();
                while (rs.next()) {
                    proc.execute(rs);
                }
    
            } finally {
                // close other resources too
                c.close();
            }
        }
    
    }
    
    
    public interface Procedure {
       void execute(T t) throws Exception;
    }
    
    
    public class ResultSetOutputStreamProcedure implements Procedure {
        private final OutputStream outputStream;
        public ResultSetOutputStreamProcedure(OutputStream outputStream) {
            this.outputStream = outputStream;
        }
    
        @Override
        public void execute(ResultSet rs) throws SQLException {
            MyBean bean = getMyBeanFromResultSet(rs);
            writeMyBeanToOutputStream(bean);
        }    
    }
    

    In this way, you keep your database connection resources inside your DAO, which is proper. But, you are not necessarily required to fill a Collection if memory is a concern.

    Hope this helps.

提交回复
热议问题