今天在測試 transaction(使用事務進行管理)的時候, 總報錯: Transaction not successfully started測試
可能有多種緣由, 這位哥們總結得很好: Transaction not successfully startedspa
個人緣由是, 將進行commit提交後,再rollback.
code
正確的作法, 應該是先rollback, 以下是完整的代碼:blog
@Test public void saveTest() { Boolean prepared = false; SessionFactory factory = null; Session s = null; Transaction t = null; try { factory = HibernateUtil.getSessionFactory(); s = factory.getCurrentSession(); t = s.beginTransaction(); Monitor m = new Monitor(); m.setFenceId("9f005029-7c0d-45d3-96c1-006d1cf94332"); m.setIMEI("862950025795124"); m.setAlllowStatus("鎖"); Date now = new Date(); m.setAllowFrom(now); m.setAllowTo(now); s.save(m); prepared = false; //表示事務的前一部分還沒作好準備. //若前一部分的事務還沒準備好,則整個事務取消. if(!prepared) { if(null != t) { System.out.println("try rollback..."); t.rollback(); } } } catch (Exception e) { if(t != null) t.rollback(); }finally { //在finally中進行提交. if(null != t) t.commit(); } }
暫時尚未好的解決方案, 由於文檔的例子, 是在catch exception的時候, rollback, 而在try 語句中進行commit.事務
可是我這個代碼, 能知足個人需求.文檔