Creating XML File With Find a particular user in the table using foreach jpa java

Asked

Viewed 64 times

0

Good morning !!

Personal my doubt is as follows

I have two tables a Person and another Employee.

I am doing a for in both tables to be able to create an XML file, but as I am not returning the results by Id but by order of for, my xml is being created but is not pulling the correct data.

the position field is pulling that of another employee as example below

Wrong

2 Rafael System Analyst

Right

2 Rafael Publisher

follows below the code to create Xml

    // Gerando Arquivo Xml Para Exportação.
private File GerarXmlFuncionarios() {

    List<FuncionarioModel> funcionariosModel = funcionarioRepository.todos();

    List<PessoaModel> pessoasModel = pessoaRepository.todas();

    // Nome do Elemento Raiz do Xml
    Element elementDados = new Element("funcionarios");

    Document documentoFuncionarios = new Document(elementDados);

    funcionariosModel.forEach(funcionario -> {
        pessoasModel.forEach(pessoa -> {
            // Campos dos Xml com os Seus Valores
            Element elementFuncionario = new Element("funcionario");
            elementFuncionario.addContent(new Element("codigo").setText(pessoa.getCodigo().toString()));
            elementFuncionario.addContent(new Element("nome").setText(pessoa.getNome()));
            elementFuncionario.addContent(new Element("cargo").setText(funcionario.getCargo()));

            elementDados.addContent(elementFuncionario);
        });
    });

    XMLOutputter xmlGerado = new XMLOutputter();
    xmlGerado.setFormat(Format.getPrettyFormat().setEncoding("ISO-8859-1"));

    try {

        // Gera o Nome do Arquivo 
        String nomeArquivo = "funcionarios_".concat(java.util.UUID.randomUUID().toString()).concat(".xml");

        // Caminho que o Arquivo Sera Salvo 
        File arquivo = new File("C:/Pasta/Sistema_Web/".concat(nomeArquivo));

        FileWriter fileWriter = new FileWriter(arquivo);

        xmlGerado.output(documentoFuncionarios, fileWriter);

        return arquivo;

    } catch (Exception ex) {

        ex.printStackTrace();
    }

    return null;
}

Pessoarepository and Funciorepository classes where I return my list of both classes

    public List<PessoaModel> todas() {
    TypedQuery<PessoaModel> query = manager.createQuery("from PessoaModel", PessoaModel.class);
    return query.getResultList();
}


    public List<FuncionarioModel> todos() {
    TypedQuery<FuncionarioModel> query = manager.createQuery("from FuncionarioModel", FuncionarioModel.class);
    return query.getResultList();
}

follows solution below functionModel.foreach(working -> { // Xml Fields with Their Values Element elementFunctioning = new Element("working"); elementFunctioning.addContent(new Element("code").setText(function.getPessoaModel().getCodigo().toString())); elementFunctioning.addContent(new Element("name").setText(funcio.getPessoaModel().getName()); elementFunctioning.addContent(new Element("position").setText(funcio.getCargo()); elementDados.addContent(elementFuncionario); });

  • It seems to me that the problem is in your pessoasModel.forEach within of funcionariosModel.forEach. You are going through the entire list of people for each employee. What is the relationship between employees and person? If there is a relationship, it would not be better to return them in a single query, since the way you are doing, there is no guarantee that the employee is related to that person specifically.

  • Hi Felipe, first thank you for answering. I know my problem is just the one you mentioned, one foreach inside another does not give me the expected result. And within my employee table I have the Id_person who would be my foreign table key person, I know it is right to make use of that key. and make only one employee and returns the person by id but do not know how could do it. if you can help me

  • From the answer you gave below, it seems that you have already solved the problem. To understand a little better how the relationship between entities works take a look at these two links on Lazy and Eager Load and Fetch Strategy.

2 answers

0

Since you do not have an effective control of each element, I suggest you perform your query in an orderly manner (ORDER BY) to have greater assurance that the correct data are moving in parallel.

Second thing is to make this interaction with the foreach of Java 8, but I don’t know how this should be done, but with an interaction with the traditional for would look something like this:

int funcionarioAdd = 0;
int pessoaAdd = 0;

for(List<FuncionarioModel> funcionario: funcionariosModel) {
 for(List<PessoaModel> pessoa: pessoasModel) {          
   if(funcionarioAdd == pessoaAdd++) {
    // Campos dos Xml com os Seus Valores
    Element elementFuncionario = new Element("funcionario");
    elementFuncionario.addContent(new Element("codigo").setText(pessoa.getCodigo()));
    elementFuncionario.addContent(new Element("nome").setText(pessoa.getNome()));
    elementFuncionario.addContent(new Element("cargo").setText(funcionario.getCargo()));
    elementDados.addContent(elementFuncionario);
    pessoaAdd = 0;
    break;
   }       
  }
 funcionarioAdd++;
}

Check the logic correctly and take care because the chances of data losing order is very high in this type of procedure (sort without keys that ensure consistency).

0

Felipe and n3uRoQuiLa, Thank you again for your help.

I could solve as below, after all I am working object oriented was simpler than I thought.

        funcionariosModel.forEach(funcionario -> {
                // Campos dos Xml com os Seus Valores
                Element elementFuncionario = new Element("funcionario");
                elementFuncionario.addContent(new Element("codigo").setText(funcionario.getPessoaModel().getCodigo().toString()));
                elementFuncionario.addContent(new Element("nome").setText(funcionario.getPessoaModel().getNome()));
                elementFuncionario.addContent(new Element("cargo").setText(funcionario.getCargo()));
                elementDados.addContent(elementFuncionario);
    });

once again grateful I hope one day I can repay

Browser other questions tagged

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