Hibernate的编程细节——事务回滚

一 事务回滚代码
private static void updateEmp() {
                //修改用户
                //获取一个会话
                /*
                Session session=MySessionFactory.getSessionFactory().openSession();
                Transaction transaction=session.beginTransaction();
                //修改用户
                //1、获取要修改的用户
                //load是通过主键属性,获取对象实例<-------->表的记录对应
                Employee employee =(Employee)session.load(Employee.class, 1);//select语句
                //2、修改
                employee.setName("xiaoming");//update
                employee.setEmail("[email protected]");
                int i=9/0;
                transaction.commit();
                session.close();
                 */
                //优化上面的代码,如何在Hibernate中回滚事务
                Session session=MySessionFactory.getSessionFactory().openSession();
                Transaction transaction=null;
                try{
                        transaction=session.beginTransaction();
                        Employee employee =(Employee)session.load(Employee.class, 1);//select语句
                        employee.setName("xiaoming");//update
                        employee.setEmail("[email protected]");
                        int i=9/0;    //构造异常
                        transaction.commit();
                }
                catch(Exception e){
                        if(transaction!=null){
                                transaction.rollback();
                        }
                        throw new RuntimeException(e.getMessage());
                }finally{
                        if(session!=null&&session.isOpen()){
                                session.close();
                        }
                }       


二 测试结果
Exception in thread "main" java.lang.RuntimeException
        at com.cakin.view.TestMain.updateEmp(TestMain.java:66)
        at com.cakin.view.TestMain.main(TestMain.java:20)

你可能感兴趣的:(Hibernate)