Error: EntityManager is closed

1

My command system, when trying to merge tables, I use EntityManager.merge, however the following error occurs: EntityManager is closed.

Here is one of the functions in my code that causes this error:

public boolean trocar_Mesa(BigDecimal origem, BigDecimal destino,String usuario) {
    ok = true;
    mensagem = "";

    Tab_Log_Troca_Mesa oMesa = null;
    Tab_Mesas oMesaOri = null;
    Tab_Mesas oMesaDest = null;
    Calendar hoje = Calendar.getInstance();
    DateTime agora = new DateTime();

    EntityManager em = JPAUtil.getEntityManager();

    try {
        em.getTransaction().begin();

        for (Tab_Comanda oComanda : (new Tab_ComandaDao())
                .listar_ComandasMesas(origem)) {
            oComanda.setNumero_Mesa(destino);
            em.merge(oComanda);
        }

public List<Tab_Comanda> listar_ComandasMesas(BigDecimal mesa)
{
    List<Tab_Comanda> oLista = null;
    ok = true;
    mensagem = "";

    String sql = 
        "select * from TAB_COMANDAS where NUMERO_MESA = :pNumeroMesa";
    EntityManager em = JPAUtil.getEntityManager();;

    try
    {
        Query query = em.createNativeQuery(sql, Tab_Comanda.class);
        query.setParameter("pNumeroMesa", mesa);
        oLista = query.getResultList();
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
        ok = false;
        mensagem = ex.getMessage();
    }
    finally{
        if (em.isOpen()){
            em.close();
        }
    }
    return oLista;
}

I did not find any forum that could help me and I'm starting now in JavaWEB, has anyone ever encountered this problem and / or know how to solve it?

Thank you in advance.

    
asked by anonymous 05.07.2016 / 02:40

1 answer

1

When using the merge you need to use the same EntityManager that you used to load the entity, but since you closed that EM shortly after listing, this error occurs. Now you need to use find to load this object and copy its new properties to save.

    
05.07.2016 / 03:06