首先最原生態的com.mysql.jdbc.Driver數據源進行回滾。
1、spring配置文件
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="url">
<value>jdbc:mysql://127.0.0.1/tbbpm_base?useUnicode=true&characterEncoding=UTF-8</value>
</property>
<property name="username">
<value>root</value>
</property>
<property name="password">
<value>123456</value>
</property>
<property name="defaultAutoCommit">
<value>false</value>
</property>
</bean>
2、測試類
package nativeTransaction;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.sql.DataSource;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:applicationContext.xml" })
public class TestDB {
/*
* 注入數據源
* */
@Autowired
protected DataSource dataSource;
@Test
public void testRollBack() throws Exception{
Connection conn = null;
try {
conn = dataSource.getConnection();
PreparedStatement pstam=null;
conn.setAutoCommit(false);//開啓事務
String sql="delete from bpm_statemachine_instance where id = 62";
pstam=conn.prepareStatement(sql);
pstam.executeUpdate();
conn.rollback();//事務回滾
conn.commit();//事務提交
}catch (Throwable e) {
if (conn != null) {
conn.rollback();
}
}
}
}
3、測試結果
我們發現執行後,ID=62的數據依然存在,假如去掉
conn.rollback();//事務回滾
後,執行發現數據已經被刪除了。說明上面例子的mysql事務回滾成功。