jdbc中利用Savepoint实现rollback
首先我们来说一下setAutoCommit,当我们设置为true或默认情况下,jdbc事务会自动提交,当我们将setAutoCommit设为false时,虽然是手动提交事务,但是如果不写手动提交代码,最后也会提交。那有什么不一样呢,例如:我们在一个方法内多次执行数据库操作,中间有根据状态或上一返回值来确定是否回滚的情况下,如果是自动提交,那回滚就不起作用,如果是手动提交状态,那回滚就有效。
接下来还是看Savepoint
con.setAutoCommit(false);Savepoint first=con.setSavepoint("first");ps=con.prepareStatement("update employees t set t.first_name='guohr1' where t.employee_id=207");flag=ps.executeUpdate();log.info("flag:"+flag);Savepoint second=con.setSavepoint("second");ps=con.prepareStatement("update employees t set t.first_name='guohr2' where t.employee_id=207");flag=ps.executeUpdate();log.info("flag:"+flag);Savepoint third=con.setSavepoint("third");ps=con.prepareStatement("update employees t set t.first_name='guohr3' where t.employee_id=207");flag=ps.executeUpdate();log.info("flag:"+flag);con.rollback(second);