Wednesday, September 24, 2014

Java SQL : Get previous item in ResultSet Iteration

Removed
I was iterating a ResultSet to  create the bean but in the While loop, I had another While as I may have tow rows having the same Id, but the assignment is different.
So in my Query I try to get information about Persons and the Job to which they was assigned in their life. So if a person worked in 3 different Jobs, by executing the SQL Query, we will get 3 rows for that person, then the other rows for other persons.
For have a better understanding here is the Code:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
while(rs.next()){
 bean = new Person();
 long personSurId = rs.getLong("person_sur_id");
 bean.setDescription(rs.getString("This is a new Person"));
  
 if (withLtJobs){
  bean.setJobAssignments(new ArrayList<PersonJobAssignment>());
  hasChilds = rs.getObject("lt_person_sur_id") != null;
  if (hasChilds){
   do{
    ob = rs.getLong("lt_person_sur_id");
    if (ob.equals(personId)){
     assignment = DAOFactory.getLtPersonJobeDAO().getBean(rs);
     bean.getJobAssignments().add(assignment);
    }else{     
     break;
    }
   }while(rs.next());
  }
 }

 result.add(bean);
}


The problem in this row is that in the the do while loop we will go through the rows. But in the Fourth iteration we will take a row that is no more for that person, so we will break and go to the principle loop where we get the next row. So the Fourth row is lost.

So I need to be able to  GET THE PREVIOUS ROW IN THE RESULTSET before going to the principle Iteration,

So in order to get the Previous Item in the ResultSet, We can use previous methood:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
  if (hasChilds){
   do{
    ob = rs.getLong("lt_person_sur_id");
    if (ob.equals(personId)){
     assignment = DAOFactory.getLtPersonJobeDAO().getBean(rs);
     bean.getJobAssignments().add(assignment);
    }else{  
     rs.previous();
     break;
    }
   }while(rs.next());
  }

Using only this call we will have an Error:

org.postgresql.util.PSQLException: Operation requires a scrollable ResultSet, but this ResultSet is FORWARD_ONLY.
at org.postgresql.jdbc2.AbstractJdbc2ResultSet.checkScrollable(AbstractJdbc2ResultSet.java:235)

Yes, in fct by Default, when we create a Statement or Prepared Statement, the Returned ResultSet is FORWARD_ONLY. So we need to create a Prepared Statement by Specifying that we need a Scrollable ResultSet.  This is done like this:


1
preparedStatement = connection.prepareStatement(sqlStatement.toString(), ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

No comments :

Post a Comment

Articles les plus consultés