Error of Session in Java

Asked

Viewed 138 times

1

I have the following methods :

public void delete(Class c, int id) throws SQLException {        
    Session session = sessionFactory.openSession();
    Transaction tx = session.beginTransaction();
    try{
        Object ob = this.getById(c, id);
        session.delete(ob);
        tx.commit();
        session.close();
    }catch(HibernateException e){
        tx.rollback();
        session.close();
        throw new SQLException(c.getName() + " - Não foi possivel excluir o registro!");
    }
}

public Object getById(Class c, Integer id) {
    Object session =  sessionFactory.getCurrentSession().get(c, id);
    return session;
}

But the following Exception is returned: Illegal Attempt to Associate a Collection with two open Sessions

What should I do ?

  • Having several sessions is costly, let’s say so. This error occurs because two sessions are open at the same time. You can: Create a single session and pass it on to your DAO(s) or use a snippet try/finally to close the session after making the transactions.

  • It seems to me that the Session object is not common to both functions, from the moment you declare it inside the delete. Try to take Session in a private class variable and not inside.

  • it is possible to put more information?

No answers

Browser other questions tagged

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