2016-12-02 27 views
0

所以我有这样的代码没有交易目前处于活动状态

public static void insert(User user) { 
    EntityManager em = DBUtil.getEmFactory().createEntityManager(); 
    EntityTransaction trans = em.getTransaction(); 
    trans.begin();   
    try { 
     em.persist(user); 
     trans.commit(); 
    } catch (Exception e) { 
     System.out.println(e); 
     trans.rollback(); 
    } finally { 
     em.close(); 
    } 
} 

但是当我跑我得到这个错误

picture

+0

后误差代码以及 – XtremeBaumer

+0

样子。请参阅:https://en.wikipedia.org/wiki/List_of_HTTP_status_codes – Flummox

回答

1

你需要首先检查如果交易活跃的感谢EntityTransaction#isActive()然后致电rollback()

非托管环境成语是:

EntityManager em = emf.createEntityManager(); 
EntityTransaction tx = null; 
try { 
    tx = em.getTransaction(); 
    tx.begin(); 

    // do some work 
    ... 

    tx.commit(); 
} 
catch (RuntimeException e) { 
    if (tx != null && tx.isActive()) tx.rollback(); 
    throw e; // or display error message 
} 
finally { 
    em.close(); 
} 

有关详情,请§5.2.1从休眠的文档。

所以你的情况的代码而应是:像服务器失去了一些东西,如,你应该有这个前送东西

EntityManager em = DBUtil.getEmFactory().createEntityManager(); 
EntityTransaction trans = null; 
try { 
    trans = em.getTransaction(); 
    trans.begin(); 
    em.persist(user); 
    trans.commit(); 
} catch (Exception e) { 
    System.out.println(e); 
    if (trans != null && trans.isActive()) 
     trans.rollback(); 
} finally { 
    em.close(); 
} 
相关问题