今天在测试 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.事务
可是我这个代码, 能知足个人需求.文档