/**
* savepoint保存点使用
* savepoint = con.setSavepoint();
*/
/**
*
* 事务处理 con.setAutoCommit(false);
* con.commit();
* con.rollback(savepoint);回滚到保存点
* con.commit();
*distributed transaction JTA
*一个分布式事务(distributed transaction)
*包括一个事务管理器(transaction manager)和一个或多个资源管理器(resource manager)。
*/
package com.study.test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Savepoint;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import org.junit.Test;
import com.study.dao.AddressService;
import com.study.dao.DaoFactory;
import com.study.dao.domain.Address;
import com.study.exceptions.DataAccessException;
import com.study.utils.JdbcUtils;
/**
*
* 事务处理 con.setAutoCommit(false);
* con.commit();
* con.rollback(savepoint);回滚到保存点
* con.commit();
*distributed transaction JTA
*一个分布式事务(distributed transaction)
*包括一个事务管理器(transaction manager)和一个或多个资源管理器(resource manager)。
*/
public class TestTransaction {
@Test
public void post() {
Connection con = null;
Statement st = null;
try {
con = JdbcUtils.getConnection();
con.setAutoCommit(false);
st = con.createStatement();
st.addBatch("update address set money=money-100 where addressid=10");
st.addBatch("update address set money=money+100 where addressid=11");
st.executeBatch();
con.commit();
} catch (SQLException e) {
try {
if (con != null)
con.rollback();
} catch (SQLException s) {
throw new DataAccessException(s.getMessage());
}
} finally {
JdbcUtils.free(null, st, con);
}
}
/**
* savepoint保存点使用
* savepoint = con.setSavepoint();
*/
@SuppressWarnings("unused")
@Test
public void savePoint() {
Connection con = null;
Statement st = null;
Savepoint savepoint = null;
try {
con = JdbcUtils.getConnection();
con.setAutoCommit(false);
st = con.createStatement();
st.executeUpdate("update address set money=money+100 where addressid=10");
savepoint = con.setSavepoint();
st.executeUpdate("update address set money=money+50 where addressid=11");
st.executeUpdate("update address set money=money+50 where addressid=12");
con.commit();
} catch (SQLException e) {
try {
if (con != null&&savepoint!=null){
con.rollback(savepoint);//回滚到保存点
con.commit();
}
} catch (SQLException s) {
throw new DataAccessException(e.getMessage());
}
} finally {
JdbcUtils.free(null, st, con);
}
}
}
JDBC事务处理和保存点
点赞
收藏