How do I add the "same" object to a list and change a property?

Asked

Viewed 50 times

0

I have to send a list of entitys to a method that will make the Insert of these entitys in the bank. This entity represents an inscription of a patient who will enter some waiting queues of different specialties. So patient John’s application to the orthopedic and cardiology line. My bank record is by specialty, so John would have two bank records, one for each specialty. The problem is that I’m not getting to put together this list with the applications by specialty. Only the first item of the List is in the List, the others are as reference to the object isncrição.

public Response cadastrarEmMultiplasEspecialidades(
            @Valid InscricaoEsperaMultiplasEspecialidadesDTO inscricaoEsperaDTO) throws URISyntaxException {

        List<InscricaoEspera> inscricoes = new ArrayList<InscricaoEspera>();


        List<Especialidade> especialidades = inscricaoEsperaDTO.getEspecialidades();


        for (Especialidade especialidade : especialidades) {
            inscricaoEspera = inscricaoEsperaDTO.getInscricaoEspera();
            inscricaoEspera.setEspecialidade(especialidade);
            int result = inscricaoEsperaService.verificaPacienteNaListaEspera(inscricaoEspera).size();

            if (result == 0) {
                 InscricaoEspera insc = new InscricaoEspera();
                 insc = inscricaoEspera;
                inscricoes.add(insc);
            } else {
                System.out.println("Paciente já cadastrado! ");
                Response.status(Response.Status.CONFLICT).build();
            }
        }

        if (!inscricoes.isEmpty()) {
            System.out.println("entrou");
            List<InscricaoEspera> inscricaoEsperaPersistido = inscricaoEsperaService.inserir(inscricoes);

            return Response.created(new URI("/inscricaoEspera/" + inscricoes)).entity(inscricaoEsperaPersistido)
                    .build();
        } else {
            System.out.println("Pau! ");
            return Response.status(Response.Status.NOT_ACCEPTABLE).build();
        }
    }

InscricaoEsperaMultiplasEspecialidadesDTO: that DTO serves for me to get a list of specialties on the front. So it’s basically an inscription and a list of specialties.

Inscribed: that’s the Entity that is saved in the bank. Its properties are the patient, the specialty, priority and date of registration.

List entries: this is the list that I pass to the written methodEsperaService.insert(entries) that executes the insertion in the bank.

When debugging, the list inscriptions adds the entries, only when inspecting the List item it is as a reference to the object inscricaoEspera, then he only gets the last specialty.

I already know that if I do a new as the parameterized constructor inside the goes and assign the properties of the inscribed.

Briefly I want to know how to avoid this behavior correctly? Is there any standard for this, especially when it comes to entitys?

1 answer

1


I’ve had this problem of references, if you don’t want to keep giving New Object in the add method of the List, you make your Subscript class ready to implement the interface Cloneable and then use the clone() method to return a copy of the values.

OR vc can create a constructor that copies the data, and use it to instantiate before adding to the List;

made an example see if it meets you:

Set the class by implementing Cloneable

public class Person implements Cloneable{
  private Integer age;
  private String name;
  private Address address;

  public Person(Integer age, String name) {
    this.age  = age;
    this.name = name;
  }

  public Person() {
  }

 //CONSTRUTOR p/ CÓPIAS 
 public Person(Person original) {
   this.age = original.age;
   this.name = new String(original.name);
   this.address = new Address(original.address);
  }

  public Person clone() throws CloneNotSupportedException {
    return (Person) super.clone();
  }

}

public class Address {
    private String street;

    public Address(String st) {
      this.street = st;
    }
    public Address(Address address) {
      this.street = address.getStreet();
    }

}

How to use:

 private static void testeList() throws CloneNotSupportedException {
          Person pessoa1 = new Person(32, "Cleber");
          List<Person> lst = new ArrayList<Person>();
          for (int i=0; i < 10; i++) {
            pessoa1.setAddress(new Address("rua "+i));
          //USANDO O CONSTRUTOR DE COPIAS
          //  Person pessoa2 = new Person(pessoa1);

            //USANDO CLONE()
            Person pessoa2 =  pessoa1.clone();
            lst.add(pessoa2);
          }
          lst.forEach( p-> System.out.println(p.getAddress().getStreet()));
          System.out.println(lst.size());
    }
  • much better than giving new

Browser other questions tagged

You are not signed in. Login or sign up in order to post.