0

I am trying to iterate over the resultset from a query but I am getting some weird behaviour I can not explain. I've been searching online and offline for a few hours now and I hope one of you can see what is causing it or might know what could cause it.

I am using Maven, JEE and JDBC.

After running a query against a MySQL database I am trying to iterate over it and add a DTO (Data Transfer Object) to a list.

class PersonDTO {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

The class in which I iterate over the results injects PersonDTO using CDI.

I can make a query without any problem but is goes wrong here (rs is the ResulSet:

List<PersonDTO> persons = new ArrayList<>();
while(rs.next())
        String name = rs.getString("name");
        System.out.println("Current name: " + name);
        PersonDTO.setName(name);
        persons.add(playlistDTO);
}

My console shows the correct result:

name: Jack
name: Doris

However in the persons array the content is Doris, Doris (The second name twice).

Piet Hein
  • 184
  • 2
  • 16

1 Answers1

2

You're overriding the name of same PersonDTO object and adding it to the list multiple times. Instead, you should create a new PersonDTO object for each iteration of the loop:

List<PersonDTO> persons = new ArrayList<>();
while(rs.next())
        String name = rs.getString("name");
        PersonDTO personDTO = new PersonDTO(); // Or use some injected factory
        personDTO.setName(name);
        persons.add(personDTO);
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350
  • That worked! Could you explain what you mean by an injected factory? I am supposed to not use the new keyword but inject everything. – Piet Hein Sep 30 '18 at 19:54
  • @PietHein I meant that instead of injecting `PersonDTO`, you could inject some `PersonDTOFactory` or `PersonDTOSupplier`, or some object that allow you to create `PersonDTO` instances. – Mureinik Sep 30 '18 at 19:55
  • Is there any way to do it while not using the new keyword anywhere? – Piet Hein Sep 30 '18 at 19:58
  • 1
    @PietHein you'll need a new object for each person. **Somewhere**, something has to call `new`. – Mureinik Sep 30 '18 at 19:59