Java Iterator backed by a ResultSet

后端 未结 17 697
清歌不尽
清歌不尽 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:16

    There are a couple of things you could do depending on what you want your class A. If the major use case is to go through every single result then perhaps its best to preload all the Entity objects and throw away the ResultSet.

    If however you don't want to do that you could use the next() and previous() method of ResultSet

    public boolean hasNext(){
           boolean next = entities.next();
    
           if(next) {
    
               //reset the cursor back to its previous position
               entities.previous();
           }
    }
    

    You do have to be careful to make sure that you arent currently reading from the ResultSet, but, if your Entity class is a proper POJO (or at least properly disconnected from ResultSet then this should be a fine approach.

提交回复
热议问题