再上一个例子中,事务如果发生回滚,会将整个事务全部撤销,如果不想全部撤销,而是只撤销其中的一部分,可以使用保存点(Savepoint)
package cn.itcast.jdbc;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.sql.Statement;
public class SavePointTest {
public static void main(String[] args) throws SQLException {
test();
}
static void test() throws SQLException {
Connection conn = null;
Statement st = null;
ResultSet rs = null;
Savepoint sp = null;
try {
conn = JdbcUtils.getConnection();
conn.setAutoCommit(false); // 关闭自动提交
st = conn.createStatement();
String sql = "update user set money =money-10 where id=1";
st.executeUpdate(sql);
sql = "update user set money =money-10 where id=3";
st.executeUpdate(sql);
sp = conn.setSavepoint(); // 设置保存点
sql = "select money from user where id=2";
rs = st.executeQuery(sql);
float money = 0.0f;
if (rs.next())
money = rs.getFloat(1);
if (money > 300)
throw new RuntimeException("超过最大值");
sql = "update user set money =money+10 where id=2";
st.executeUpdate(sql);
conn.commit(); // 提交
} catch (RuntimeException e) {
if (conn != null && sp != null) {
conn.rollback(sp); // 出现异常,回滚到sp
conn.commit();
}
throw e;
} catch (SQLException e) {
if (conn != null)
conn.rollback(); // 出现异常,回滚
throw e;
} finally {
JdbcUtils.free(rs, st, conn);
}
}
}
在这个例子中如果发生了异常,那么id=1和id=2的操作不会被撤销,事务只回滚到Savepoint的位置。