@Test public void testTx() { SessionFactory sessionFactory = null; Session session = null; Transaction tx = null; try { sessionFactory = HibernateUtils.getSessionFactory(); session = sessionFactory.openSession(); //开启事务 tx = session.beginTransaction(); //添加 User user = new User(); user.setUsername("小马"); user.setPassword("250"); user.setAddress("美国"); session.save(user); int i = 10/0; //提交事务 tx.commit(); }catch(Exception e) { e.printStackTrace(); //回滚事务 tx.rollback(); }finally { //关闭操作 session.close(); sessionFactory.close(); } }