JdbcTemplate事務開啟的正確方式
阿新 • • 發佈:2021-02-19
場景復現,使用JdbcTemplate操作資料庫,採用如下方式開啟事務,然而並無卵用
/**
* 事務開啟無效
* @throws SQLException
*/
@Test
public void fun5() throws SQLException {
//獲取JdbcTemplate
JdbcTemplate jdbcTemplate = JDBCUtil.getJdbcTemplate();
//獲取連線
Connection connection = jdbcTemplate.getDataSource().getConnection();
//關閉自動提交
connection.setAutoCommit(false);
boolean autoCommit = connection.getAutoCommit();
String sql1 = "insert into mydb.user (id,username,sex) values ('1','zs','男');";
String sql2 = "insert into mydb.user (id,username,sex) values ('11','ws','女')" ;
try {
//執行sql(其中sql1的id是重複的)
int[] rs2 = jdbcTemplate.batchUpdate(new String[]{sql1, sql2});
//提交執行
connection.commit();
}catch (SQLException e){
e.printStackTrace();
//異常回滾
connection.rollback();
} finally {
connection.setAutoCommit(autoCommit);
if(connection != null){
connection.close();
}
}
}
控制檯異常
org.springframework.dao.DuplicateKeyException: StatementCallback; SQL [insert into mydb.user (id,username,sex) values ('1','zs','男');]; Duplicate entry '1' for key 'PRIMARY'; nested exception is java.sql.BatchUpdateException: Duplicate entry '1' for key 'PRIMARY'
at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:243)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:72)
at org.springframework.jdbc.core.JdbcTemplate.translateException(JdbcTemplate.java:1443)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:388)
at org.springframework.jdbc.core.JdbcTemplate.batchUpdate(JdbcTemplate.java:590)
at com.syx.TestFunction.fun5(TestFunction.java:96)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:68)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.junit.runner.JUnitCore.run(JUnitCore.java:157)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: java.sql.BatchUpdateException: Duplicate entry '1' for key 'PRIMARY'
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at com.mysql.cj.util.Util.handleNewInstance(Util.java:192)
at com.mysql.cj.util.Util.getInstance(Util.java:167)
at com.mysql.cj.util.Util.getInstance(Util.java:174)
at com.mysql.cj.jdbc.exceptions.SQLError.createBatchUpdateException(SQLError.java:224)
at com.mysql.cj.jdbc.StatementImpl.executeBatchInternal(StatementImpl.java:911)
at com.mysql.cj.jdbc.StatementImpl.executeBatch(StatementImpl.java:814)
at org.springframework.jdbc.core.JdbcTemplate$1BatchUpdateStatementCallback.doInStatement(JdbcTemplate.java:550)
at org.springframework.jdbc.core.JdbcTemplate$1BatchUpdateStatementCallback.doInStatement(JdbcTemplate.java:536)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:376)
... 24 more
Caused by: java.sql.SQLIntegrityConstraintViolationException: Duplicate entry '1' for key 'PRIMARY'
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:117)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.StatementImpl.executeUpdateInternal(StatementImpl.java:1355)
at com.mysql.cj.jdbc.StatementImpl.executeBatchInternal(StatementImpl.java:877)
... 28 more
控制檯報了一個java.sql.BatchUpdateException: Duplicate entry ‘1’ for key ‘PRIMARY’,即主鍵衝突。我們在程式碼裡開啟了事務,按理來說sql2 應該不執行才對,但是奇怪的是它執行了,而且資料庫有新增記錄。
正確開啟事務的方式
/**
* 解決事務問題
* @throws SQLException
*/
@Test
public void fun6() throws SQLException {
TransactionSynchronizationManager.initSynchronization();
JdbcTemplate jdbcTemplate = JDBCUtil.getJdbcTemplate();
DataSource dataSource = jdbcTemplate.getDataSource();
Connection connection = DataSourceUtils.getConnection(dataSource);
connection.setAutoCommit(false);
boolean autoCommit = connection.getAutoCommit();
String sql1 = "insert into mydb.user (id,username,sex) values ('1','zs','男');";
String sql2 = "insert into mydb.user (id,username,sex) values ('11','ws','女')";
try {
int[] rs2 = jdbcTemplate.batchUpdate(new String[]{sql1, sql2});
connection.commit();
}catch (SQLException e){
e.printStackTrace();
connection.rollback();
}finally {
connection.setAutoCommit(autoCommit);
if(connection != null){
connection.close();
}
}
}