'Transaction is not active' after receiving error for not being able to delete

1

Galera was tempted to set up a crud for study and I came across the following situation.

I'm using JPA and Hibernate.

When trying to delete a record which has a reference in another table, an Exception is thrown saying that it can not delete because it has reference, until there it is ok.

After this Exception appears if I try to add another item appears the same exception that showed when I tried to delete and just below 'Transaction is not active' what could be happening?

DAO

public T inserir(T entity) throws Exception {
    try {
        manager.getTransaction().begin();
        manager.persist(entity);
        manager.getTransaction().commit();          
    } catch (Exception e) {
        manager.getTransaction().rollback();
    }
    return entity;
}'

public void excluir(T entity) {
    try {
        manager.getTransaction().begin();
        manager.remove(entity);
        manager.getTransaction().commit();
    } catch (Exception e) {
        manager.getTransaction().rollback();
    }
}

RN

public Item inserir(Item item){
    try {
        return geralDAO.inserir(item);
    } catch (Exception e) {
        System.err.println(e.getMessage());
        return null;
    }       
}

public void excluir(Item item){
    try {
        geralDAO.excluir(item);

    } catch (Exception e) {
        System.err.println("Erro ao deletar", e.getMessage());          
    }       
}
    
asked by anonymous 28.07.2016 / 15:49

1 answer

1

You are probably creating factory and manager in construtor , but with each operation, it must be closed conexão . The "correct" implementation would be to create the factory and the manager in each method, and close them after the operation.

Ex:

public void setProdutos(ProdutosVO produto) throws Exception{
    try {
        EntityManagerFactory factory = Persistence.createEntityManagerFactory("model");
        EntityManager manager = factory.createEntityManager();

        manager.getTransaction().begin();    
        manager.persist(produto);
        manager.getTransaction().commit();  

    } catch (Exception e) { 
        throw new Exception(e);
    }finally {
        manager.close();
        factory.close();
    }
}
    
28.07.2016 / 16:19