hibernate事务规范写法

@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();
        }
    }

 

posted @ 2018-09-13 19:35  SteveYu  阅读(255)  评论(0编辑  收藏  举报