Error: Entitymanager is closed

Asked

Viewed 477 times

1

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

Follows one of the functions of my code that occurs 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);
        }

It also follows the function Javascript list_ComandasIf I can help, but as I noticed it is returning the list correctly, I believe the error is not in it...

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 couldn’t find any forum that could help me and I’m starting now on Javaweb, someone has come across this problem and/or knows how to solve it?

Thanks in advance.

1 answer

1

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

  • So, Julio, thanks for the tip, but I had forgotten to quote the following... I was already running this application with a Sqlserver database and worked normally, then I did the conversion of this database to Mysql, made the necessary adjustments in the application to connect to the Mysql database, and just stopped working this part... You’d know how to help me?

  • Good guy, as far as I know this error occurs independent of database, if it worked before, so I wouldn’t know how to help you, I hope someone else shows up to try to solve.

  • Oh beauty then... Even so, I’ll see if I understand and try to do what you gave me by solving my problem is what matters kkkkk Thank you.

Browser other questions tagged

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