Exclui dados da aplicação, mas não do banco, usando JPA

Aê pessoal,

numa aplicação desktop os dados são excluídos e quando vou listar eles não aparecem… até aí tudo bem

O problema é quando vou ver lá no PostgreSQL, os dados continuam lá…

Alguma dica de como resolver?

Segue o código

private void jButton36ActionPerformed(java.awt.event.ActionEvent evt) {                                          

        int index = jTable5.getSelectedRow();

        if (index >= 0) {

            int escolha = JOptionPane.showConfirmDialog(jDialog7, "Tem certeza que deseja remover esse representante?", "Aviso", JOptionPane.YES_NO_OPTION);

            if (escolha == JOptionPane.YES_OPTION) {

                String nome = (String) jTable5.getValueAt(indice, 0);

                DAORepresentante daoRepresentante = new DAORepresentante();
                daoRepresentante.begin();
                //int retorno = daoRepresentante.removeByNome(nome);
                List<Representante> representantes = daoRepresentante.findByField("nome", nome);
                daoRepresentante.close();

                Representante representante = representantes.get(0);

                daoRepresentante = new DAORepresentante();
                daoRepresentante.begin();
                representante.setEmpresa(null);
                representante.setDocumentos(null);
                representante = daoRepresentante.merge(representante); //aqui
                daoRepresentante.remove(representante);
                daoRepresentante.commit();
                daoRepresentante.close();

                this.modeloRepresentante.removeRow(indice);

            }

        } else {

            JOptionPane.showMessageDialog(jDialog7, "Nenhum representante selecionado", "Aviso", JOptionPane.INFORMATION_MESSAGE);
        }
    } 

Posta o código do DAO, ficará mais fácil de ajudar.

taí o DAORepresentante

public class DAORepresentante extends DAOJPA<Representante> {

    public DAORepresentante() {
        super();
    }

    public int removeByNome(String nome){

        Query query = super.getManager().createQuery("DELETE FROM Representante r WHERE r.nome LIKE '" + nome + "'");
        return query.executeUpdate();
    }
}

e o DAOJPA

public class DAOJPA<T> implements DAOInterface<T> {

    protected static EntityManager manager;

    protected DAOJPA() {
        manager = getManager();
    }

    protected static EntityManager getManager() {
        if (manager == null) {
            EntityManagerFactory factory = Persistence.createEntityManagerFactory("cartorio");
            manager = factory.createEntityManager();
        }
        return manager;
    }

    public void persist(T obj) {
        getManager().persist(obj);
    }

    public void remove(T obj) {
        getManager().remove(obj);
    }

    public T merge(T obj) {
        return getManager().merge(obj);
    }

    public void refresh(T obj) {
        getManager().refresh(obj);
    }

    public void flush() {
        getManager().flush();
    }

    @SuppressWarnings("unchecked")
    public T find(Object chave) {
        Class<T> type = (Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        return getManager().find(type, chave);
    }

    @SuppressWarnings("unchecked")
    public List<T> findAll() {
        Class<T> type = (Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        Query query = getManager().createQuery("select x from " + type.getSimpleName() + " x");
        return (List<T>) query.getResultList();
    }

    @SuppressWarnings("unchecked")
    public synchronized List<T> findByField(String campo, String valor) {
        Class<T> type = (Class<T>) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        Query query = getManager().createQuery("select x from " + type.getSimpleName() + " x "
                + "where x." + campo + " = \"" + valor + "\"");
        return (List<T>) query.getResultList();
    }

    public void close() {
        if (getManager().isOpen()) {
            manager = null;
        }
    }

    public void begin() {
        if (!getManager().getTransaction().isActive()) {
            getManager().getTransaction().begin();
        }
    }

    public void commit() {
        if (getManager().getTransaction().isActive()) {
            getManager().getTransaction().commit();
        }
    }

    public void rollback() {
        if (getManager().getTransaction().isActive()) {
            getManager().getTransaction().rollback();
        }
    }

    //----------------------------------------------------------
    //----------------------- USO DE JPQL ----------------------
    //----------------------------------------------------------
    public Object findByQuery(String consultaJPQL) {
        try {
            Query q = getManager().createQuery(consultaJPQL);
            return (Object) q.getSingleResult();
        } catch (NoResultException e) {
            return null;
        } catch (NonUniqueResultException e) {
            return null;
        }
    }

    public List findAllByQuery(String consulta) {
        try {
            Query q = getManager().createQuery(consulta);
            return q.getResultList();
        } catch (NoResultException e) {
            return null;
        } catch (NonUniqueResultException e) {
            return null;
        }
    }

    public List findAgregateByQuery(String consulta) {
        Query q = getManager().createQuery(consulta);
        return q.getResultList();
    }

    @SuppressWarnings("unchecked")
    public int updadeAll(String consulta) {
        getManager().getTransaction().begin();
        Query q = getManager().createQuery(consulta);
        int linhas = q.executeUpdate();
        getManager().getTransaction().commit();
        return linhas;

    }
}

Pode ser que não resolva, mas tenta assim:

 public  void remove(T obj) {  
         begin();
         EntityManager em=getManager();
         obj=em.merge(obj);
         em.remove(obj);
         commit();
   }



[quote=Daniel.F]Pode ser que não resolva, mas tenta assim:

[code]
public void remove(T obj) {
begin();
EntityManager em=getManager();
obj=em.merge(obj);
em.remove(obj);
commit();
}

[/code][/quote]

Daniel obrigado por responder

Aparentemente está resolvido.

O problema agora é outro: supomos que eu cadastre os representantes A, B e C. Caso eu tente excluir o B ou C, acaba sendo excluído o A. Então o que ocorre é que sempre acaba excluindo o 1º registro do List.

Alguém sugere algo?

Pouco foi modificado do código, mas está baixo

private void jButton36ActionPerformed(java.awt.event.ActionEvent evt) {                                          

        int index = jTable5.getSelectedRow();

        if (index >= 0) {

            int escolha = JOptionPane.showConfirmDialog(jDialog7, "Tem certeza que deseja remover esse representante?", "Aviso", JOptionPane.YES_NO_OPTION);

            if (escolha == JOptionPane.YES_OPTION) {

                String nome = (String) jTable5.getValueAt(indice, 0);

                DAORepresentante daoRepresentante = new DAORepresentante();

                List<Representante> representantes = daoRepresentante.findByField("nome", nome);

                Representante representante = representantes.get(0);

                daoRepresentante.begin();
                representante.setEmpresa(null);
                representante.setDocumentos(null);
                representante = daoRepresentante.merge(representante);
                daoRepresentante.remove(representantes.get(0));
                //daoRepresentante.remove(representante);
                daoRepresentante.commit();
                daoRepresentante.close();

                this.modeloRepresentante.removeRow(indice);

            }

        } else {

            JOptionPane.showMessageDialog(jDialog7, "Nenhum representante selecionado", "Aviso", JOptionPane.INFORMATION_MESSAGE);
        }
    }                          

A variável representantes é uma lista? Se sim, como você a preenche??

sim Daniel, é uma lista List<Representante> representantes = daoRepresentante.findByField(“nome”, nome);

No DAOJPA essa lista é preenchida e retornada por esse método

@SuppressWarnings("unchecked")
    public synchronized List&lt;T&gt; findByField(String campo, String valor) {
        Class&lt;T&gt; type = (Class&lt;T&gt;) ((ParameterizedType) this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        Query query = getManager().createQuery("select x from " + type.getSimpleName() + " x "
                + "where x." + campo + " = \"" + valor + "\"");
        return (List&lt;T&gt;) query.getResultList();
    }

quanto ao preenchimento vc se refere, a como esses dados são cadastrados?