Problem when performing a select with JPA

Asked

Viewed 58 times

0

I’m facing a bug I can’t figure out a solution.

When I do a persist and then select the received and normal result, but when doing an update and after that select instead of displaying the updated result the result of select are the old values, needing to close the program and open again to test. Below is the DAO developed to verify what may be causing the problem.

public class ApartamentoDAO {
private EntityManager em;

/**
 * Contrutor para receber o Entity Manager
 * @param em -  parametro que recebe o Entity Manager
 */
public ApartamentoDAO(EntityManager em) {
    this.em = em;
}

/**
 * 
 * @param apt - Recebe o id do apartamento para verifica se existe no banco de dados.
 * 
 * @return ap - retorna um Apartamento existente no banco, ou retorna null.
 */
public Apartamento pesquisarAp(long apt) {
    System.out.println("o long da pesquisa e esse: " + apt);
    Apartamento ap = null;

    try {
        em.getTransaction().begin();
        ap = em.find(Apartamento.class, apt);
                em.getTransaction().commit();
                System.out.println("o apartamento e esse: "+ap.getId());
    } catch (Exception e) {
        System.out.println("o erro em questão foi esse: "+e);
    }
    return ap;

}

/**
 * Inserir um novo Apartamento
 * @param numero - id
 * @param andar - andar
 * @param descricao - descrição
 * @param valor  - valor do Ap
 * @param quantidade  - quantidade de hospede no Ap
 * @param ala - Ala onde se encontar o Ap
 */
public void inserirAp(Long numero, Long andar, String descricao, BigDecimal valor, Long quantidade, String ala) {

    em.getTransaction().begin();

    Apartamento ap = new Apartamento(numero, andar, descricao, valor, quantidade, ala);
    em.persist(ap);

    em.getTransaction().commit();
}

/**
 * Alterar o Apartamento selecionado
 * @param numero - id
 * @param andar - andar
 * @param descricao - descrição
 * @param valor
 * @param quantidade
 * @param ala
 */
public void alterarAp(Long numero, long andar, String descricao, BigDecimal valor, Long quantidade, String ala) {
    em.getTransaction().begin();

    Apartamento ap = new Apartamento(numero, andar, descricao, valor, quantidade, ala);

    em.merge(ap);


    em.getTransaction().commit();
    em.close();

}

/**
 * Lista todos os apartamentos existentes
 * 
 * @return resultado - retorna todos os apartamentos
 */
public List<Apartamento> listarAp() {
    em.getTransaction().begin();

    String sql = "select a from Apartamento a";

    TypedQuery<Apartamento> query = em.createQuery(sql, Apartamento.class);


    List<Apartamento> resultado = query.getResultList();

    for (Apartamento result : resultado) {
        System.out.println(result.getId());
        System.out.println(result.getAndar());
        System.out.println(result.getDescricao());
        System.out.println(result.getValor());
        System.out.println("esse e o listar simples");
    }

    em.getTransaction().commit();


    return resultado;

}

public void deletarAp(long apt) {
    em.getTransaction().begin();

    Apartamento ap =em.find(Apartamento.class, apt);
    em.remove(ap);

    em.getTransaction().commit();
}




public List<Apartamento> listarAp(String disponivel, Long apt) {
    em.getTransaction().begin();

    String sql = "select a from Apartamento a where a.status = :cDispo";

    TypedQuery<Apartamento> query =(TypedQuery<Apartamento>) em.createQuery(sql);
    query.setParameter("cDispo", disponivel);
    List<Apartamento> resultado = query.getResultList();

    sql = "select a from Apartamento a where a.id = :cApt";
    TypedQuery<Apartamento> query1 = (TypedQuery<Apartamento>) em.createQuery(sql);
    query1.setParameter("cApt", apt);
    Apartamento ap = query1.getSingleResult();
    resultado.add(ap);

    for (Apartamento result : resultado) {
        System.out.println(" esse e o resultado da querry do banco de dados "+result.getId());
    }

    em.getTransaction().commit();

    return resultado;
}


    }

Exhibition Class:

public class TelaPesq extends javax.swing.JInternalFrame {

EntityManager em;
List<Apartamento> listaAp;
JDesktopPane panel;

private Component getInstance() {
    return this;
}
/**
 * Creates new form TelaPesq
 *
 * @param panel
 */
public TelaPesq(JDesktopPane panel) {
    this.panel = panel;
    initComponents();
    menu();
    em = new JPAUtil().getEM();
}

/**
 * This method is called from within the constructor to initialize the form.
 * WARNING: Do NOT modify this code. The content of this method is always
 * regenerated by the Form Editor.
 */
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">                          
private void initComponents() {

    jPanel1 = new javax.swing.JPanel();
    jPanel2 = new javax.swing.JPanel();
    cbxAp = new javax.swing.JComboBox<>();
    jLabel1 = new javax.swing.JLabel();
    jScrollPane1 = new javax.swing.JScrollPane();
    txaConteudo = new javax.swing.JTextArea();
    btnEdit = new javax.swing.JButton();
    bntDelete = new javax.swing.JButton();

    setClosable(true);
    setIconifiable(true);
    setMaximizable(true);
    setResizable(true);
    setTitle("Visualizar");
    addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
        public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
            formInternalFrameActivated(evt);
        }
        public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
        }
        public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
        }
        public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
        }
        public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
        }
        public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
        }
        public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
        }
    });

    jPanel1.setBackground(new java.awt.Color(253, 244, 227));

    jPanel2.setBackground(new java.awt.Color(204, 204, 204));

    cbxAp.addItemListener(new java.awt.event.ItemListener() {
        public void itemStateChanged(java.awt.event.ItemEvent evt) {
            cbxApItemStateChanged(evt);
        }
    });

    jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
    jLabel1.setText("Apartamentos");

    txaConteudo.setEditable(false);
    txaConteudo.setColumns(20);
    txaConteudo.setRows(5);
    jScrollPane1.setViewportView(txaConteudo);

    btnEdit.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
    btnEdit.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/icons8-Edit-32.png"))); // NOI18N
    btnEdit.setText("Editar");
    btnEdit.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            btnEditActionPerformed(evt);
        }
    });

    bntDelete.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
    bntDelete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/img/icons8-Delete Bin-32.png"))); // NOI18N
    bntDelete.setText("Excluir");
    bntDelete.addActionListener(new java.awt.event.ActionListener() {
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            bntDeleteActionPerformed(evt);
        }
    });

    javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
    jPanel2.setLayout(jPanel2Layout);
    jPanel2Layout.setHorizontalGroup(
        jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel2Layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jScrollPane1)
                .addGroup(jPanel2Layout.createSequentialGroup()
                    .addComponent(jLabel1)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(cbxAp, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(0, 518, Short.MAX_VALUE))
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                    .addGap(0, 0, Short.MAX_VALUE)
                    .addComponent(btnEdit)
                    .addGap(18, 18, 18)
                    .addComponent(bntDelete)))
            .addContainerGap())
    );
    jPanel2Layout.setVerticalGroup(
        jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel2Layout.createSequentialGroup()
            .addGap(19, 19, 19)
            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(jLabel1)
                .addComponent(cbxAp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(32, 32, 32)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 249, Short.MAX_VALUE)
            .addGap(18, 18, 18)
            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                .addComponent(btnEdit)
                .addComponent(bntDelete))
            .addContainerGap())
    );

    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addContainerGap())
    );
    jPanel1Layout.setVerticalGroup(
        jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel1Layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addContainerGap())
    );

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    );

    setBounds(0, 0, 754, 442);
}// </editor-fold>                        

private void cbxApItemStateChanged(java.awt.event.ItemEvent evt) {                                       
    escrever();        // TODO add your handling code here:
}                                      

private void btnEditActionPerformed(java.awt.event.ActionEvent evt) {                                        
    editar();        // TODO add your handling code here:
}                                       

private void bntDeleteActionPerformed(java.awt.event.ActionEvent evt) {                                          
    deletarAP();        // TODO add your handling code here:
}                                         

private void formInternalFrameActivated(javax.swing.event.InternalFrameEvent evt) {                                            
    pesquisarAp();        // TODO add your handling code here:
}                                           


// Variables declaration - do not modify                     
private javax.swing.JButton bntDelete;
private javax.swing.JButton btnEdit;
private javax.swing.JComboBox<String> cbxAp;
private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel jPanel2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea txaConteudo;
// End of variables declaration                   

/**
 * Metodo usado quando o Frame inicia para listar os apartamentos existentes
 */
private void pesquisarAp() {
    ApartamentoDAO dao = new ApartamentoDAO(em);
    listaAp = dao.listarAp();

    DefaultComboBoxModel ap = new DefaultComboBoxModel();

    listaAp.forEach((apt) -> {
        ap.addElement(apt.getId());
    });
    cbxAp.setModel(ap);

    escrever();

}

/**
 * Escrever na Area de texto as informaçoes pertinentes ao Apartamento
 */
private void escrever() {
    for (Apartamento apt : listaAp) {
        if (apt.getId() == Integer.parseInt(cbxAp.getSelectedItem().toString())) {
            txaConteudo.setText(
                    "Andar do apartamento: "        + apt.getAndar()        + "\n\n"
                    + "Valor do Apartamento: R$ "   + apt.getValor()        + "\n\n"
                    + "Quantidade de quartos: "     + apt.getQuantidade()   + "\n\n"
                    + "Ala: "                       + apt.getAla()          + "\n\n"
                    + "Descrição: \n"
                    + apt.getDescricao());
        }
    }
}


/**
 * Botão que encaminha para o formApart para alterar o apartamento
 */
private void editar() {
    TelaApart tela = new TelaApart();
    panel.add(tela);
    tela.alterar = true;
    if (cbxAp.getSelectedItem() != null) {
        Long apt = Long.parseLong(cbxAp.getSelectedItem().toString());
        tela.apt = apt;
        this.setVisible(false);
        tela.setVisible(true);
    } else {
        JOptionPane.showMessageDialog(null, "Não existe apartamento para ser editado!");
    }
}

/**
 * Botão que deleta o partamento selecionado
 */
private void deletarAP() {
    if (cbxAp.getSelectedItem() != null) {
        int aviso = JOptionPane.showConfirmDialog(
                null,
                "Tem certeza que deseja remover esse apartamento?",
                "Atenção",
                JOptionPane.YES_NO_OPTION);

        if (aviso == JOptionPane.YES_OPTION) {
            ApartamentoDAO dao = new ApartamentoDAO(em);
            dao.deletarAp(Long.parseLong(cbxAp.getSelectedItem().toString()));
            JOptionPane.showMessageDialog(null, "Apartamento Deletado com Sucesso!");

            pesquisarAp(); 
        }
    } else {
        JOptionPane.showMessageDialog(null, "Não existe apartamento para ser deletado!");
    }

}

private void menu() {
    setDefaultCloseOperation(javax.swing.JInternalFrame.DO_NOTHING_ON_CLOSE);
    addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
        @Override
        public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
            formInternalFrameActivated(evt);
        }

        @Override
        public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
            System.out.println("teste closed");
        }

        @Override
        public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
            int option = JOptionPane.showConfirmDialog(null, "Quer mesmo fechar essa janela?", "Fechar Janela",
                    JOptionPane.YES_NO_OPTION);
            if (option == JOptionPane.YES_OPTION) {
                //call dispose to really close it
                dispose();
            }
        }

        @Override
        public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            System.out.println("teste deactivated");
        }

        @Override
        public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            System.out.println("teste deiconfied");

        }

        @Override
        public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {

            moveToFront();
        }

        @Override
        public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
            System.out.println("teste opened");

        }

    });

}

}

Entity Class

 @Entity
 public class Apartamento implements Serializable {


@Id

private Long id;

private Long andar;

private String descricao;

private BigDecimal valor;

private Long quantidade;

private String ala;

@OneToMany(mappedBy = "apartamento")
private List<Hospede> hospede;

public Apartamento() {
}

public Apartamento(Long id, Long andar, String descricao, BigDecimal valor, Long quantidade, String ala) {
    this.id = id;
    this.andar = andar;
    this.descricao = descricao;
    this.valor = valor;
    this.quantidade = quantidade;
    this.ala= ala;
}





public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

public Long getAndar() {
    return andar;
}

public void setAndar(Long andar) {
    this.andar = andar;
}

public String getDescricao() {
    return descricao;
}

public void setDescricao(String descricao) {
    this.descricao = descricao;
}

public BigDecimal getValor() {
    return valor;
}

public void setValor(BigDecimal valor) {
    this.valor = valor;
}

public Long getQuantidade() {
    return quantidade;
}

public void setQuantidade(Long quantidade) {
    this.quantidade = quantidade;
}

public List<Hospede> getHospede() {
    return hospede;
}

public void setHospede(List<Hospede> hospede) {
    this.hospede = hospede;
}

public String getAla() {
    return ala;
}

public void setAla(String ala) {
    this.ala = ala;
}

}

Telaapart class

private void salvarAP(boolean alterar) {

    if (txtNumero.getText().equals("")) {
        JOptionPane.showMessageDialog(null, "Por favor, preencha todas as informações contendo (*)");
        marcacao();
    } else {

        txtDiaria.setText(txtDiaria.getText().replace(",", "."));
        Long numero = Long.parseLong(txtNumero.getText());
        ApartamentoDAO dao = new ApartamentoDAO(em);
        Apartamento ap = dao.pesquisarAp(numero);

        if (alterar && ap != null) {
            alterarAP(dao, numero);

        } else if (!alterar && ap != null) {
            int aviso = JOptionPane.showConfirmDialog(
                    null,
                    "Tem certeza que deseja alterar as informaçoes desse apartamento?",
                    "Aviso, Apartamento Existente!",
                    JOptionPane.YES_NO_OPTION);

            if (aviso == JOptionPane.YES_OPTION) {
                alterarAP(dao, numero);

            }
        } else {
            int aviso = JOptionPane.showConfirmDialog(
                    null,
                    "Tem certeza que deseja cadastrar esse apartamento?",
                    "Aviso!",
                    JOptionPane.YES_NO_OPTION);

            if (aviso == JOptionPane.YES_OPTION) {
                BigDecimal diaria;
                if(txtDiaria.getText().equals("")){
                    diaria = new BigDecimal(BigInteger.ZERO);
                }else{
                 diaria =  new BigDecimal(txtDiaria.getText());
                }

                dao.inserirAp(Long.parseLong(txtNumero.getText()),
                        Long.parseLong(cbxAndar.getSelectedItem().toString()),
                        txaDesc.getText(),
                        diaria,
                        Long.parseLong(cbxQtd.getSelectedItem().toString()),
                        cbxAla.getSelectedItem().toString());
                JOptionPane.showMessageDialog(null, "O Apartamento foi incluido com sucesso!");
                limpar();
            }
        }
    }

}

/**
 * Metodo usado para alterar um apartamento ja existente.
 *
 * @param dao - chamar o metodo alterarAP do ApartamentoDAO
 * @param numero - id do apartamento
 */
private void alterarAP(ApartamentoDAO dao, Long numero) {
    dao.alterarAp(
            numero,
            Long.parseLong(cbxAndar.getModel().getSelectedItem().toString()),
            txaDesc.getText(),
            new BigDecimal(txtDiaria.getText()),
            Long.parseLong(cbxQtd.getModel().getSelectedItem().toString()),
            cbxAla.getModel().getSelectedItem().toString()

    );
    JOptionPane.showMessageDialog(null, "O Apartamento foi alterado com sucesso!");
    limpar();
}

/**
 * Metodo para limpar todos os campos de textos
 */
private void limpar() {
    txtNumero.setEditable(true);
    txtDiaria.setText("");
    txaDesc.setText("");
    txtNumero.setText("");
    txtNumero.setBackground(Color.WHITE);
    txtDiaria.setBackground(Color.WHITE);
    cbxAla.setSelectedIndex(0);
    cbxAndar.setSelectedIndex(0);
    cbxQtd.setSelectedIndex(0);

}

/**
 * Pesquisar o apartamento que deve ser alterado
 *
 * @param apt - numero do apartamento a ser pesquisado
 */
public void pequisarAP(long apt) {
    if (apt != 0l) {
        ApartamentoDAO dao = new ApartamentoDAO(em);
        Apartamento ap = dao.pesquisarAp(apt);
        System.out.println(ap.getDescricao());

        this.txtNumero.setText(ap.getId().toString());
        this.txtDiaria.setText(ap.getValor().toString());
        this.txaDesc.setText(ap.getDescricao());
        this.cbxAndar.setSelectedItem(ap.getAndar());
        txtNumero.setEditable(false);
    }

}

The Apart Screen is only the methods because the rest of the code did not fit in the maximum limit of the text.

  • Put the class TelaApart please.

1 answer

1

You are closing your EntityManager after changing the data of the Apartamento:

public void alterarAp(Long numero, long andar, String descricao, BigDecimal valor, Long quantidade, String ala) {
    em.getTransaction().begin();

    Apartamento ap = new Apartamento(numero, andar, descricao, valor, quantidade, ala);
    em.merge(ap);
    em.getTransaction().commit();
    em.close(); /*Remova essa linha*/
}

Remove the marked line.

Also, due to the way you shaped your application, you need to evoke the method pesquisarAp() after editing the entity to update its list.

  • Whether or not the problem persists.

  • @Julianosilveira What are the other classes of the project? Because I tested here the class you put and worked normally.

  • added to Entity and Project Display Screen

  • @Julianosill you have tried to store the returned object by merge and use it to check if the values are updated?

  • @Julianosilveira You have to evoke the method pesquisarAp() to update your list.

  • I invoke, when changing I open the search screen again and when it opens the method pesquisarAp() and run, but it looks like JPA instead of accessing the database to select it looks at some kind of cache and does not display the update. According to my research the fact of changing screen to perform the merge that being somehow causing this problem

  • @Julianosilveira O merge creates a new object with the changes and returns it. It would only cause the problem if you were not performing the SELECT again. Try to put a System.out.println() with some message on pesquisarAp() to make sure it is running by changing some entity.

  • yes, the merge is doing the update, when I check the bank the change is there.

Show 3 more comments

Browser other questions tagged

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