dari1495
dari1495

Reputation: 289

How to turn a ResultSet into a DTO ArrayList

I have a ResultSet from a Database that contains 6 columns for each row.

For me, each row is an object and each column is a parameter for that object.

The question is, I'm trying to do it with this code:

while(rs.next() && i<25){
        aux.setIdVinilo(rs.getInt("id_vinilo"));
        aux.setTitulo(rs.getString("titulo"));
        aux.setAutor(rs.getString("autor"));
        aux.setGenero(rs.getString("genero"));
        aux.setFecha(rs.getInt("fecha"));
        aux.setDiscografica(rs.getString("discografica"));
        aux.setImagen(rs.getString("imagen"));

        historial.add(aux);
        i++;
    } 

rs is the ResultSet, historial is the ArrayList and aux is my DTO consisting of the fields shown.

The problem with this is that it ends up filling the ArrayList with the same information 25 times. So I guess that rs.next() does not move one row forward after each iteration. How do I achieve this?

Upvotes: 2

Views: 1349

Answers (2)

VALARMATHI
VALARMATHI

Reputation: 41

Create DTO object inside the while loop

Upvotes: 0

SpringLearner
SpringLearner

Reputation: 13854

The problem is you are setting the same object again and again You need to create a new object inside loop

while(rs.next() && i<25){                    
        DTO aux=new DTO();// create aux object here

        aux.setIdVinilo(rs.getInt("id_vinilo"));
        aux.setTitulo(rs.getString("titulo"));
        aux.setAutor(rs.getString("autor"));
        aux.setGenero(rs.getString("genero"));
        aux.setFecha(rs.getInt("fecha"));
        aux.setDiscografica(rs.getString("discografica"));
        aux.setImagen(rs.getString("imagen"));

        historial.add(aux);
        i++;
} 

Upvotes: 8

Related Questions