前言
在spring jdbcTemplate 事务,各种诡异,包你醍醐灌顶!最后遗留了一个问题:spring是如何保证同个事务的?
当然,spring事务内容挺多的,如果都要讲的话要花很长时间,而本片博客的主旨是解决上一篇博客遗留的问题,那么我们把问题细化下来, 就是spring如何保证一个事务中的jdbc connection是同一个?
没有事务
如若没有事务,这个很好理解,可以理解成spring只是对我们一般的jdbc操作进行了一些封装,减少了我们的代码量
1、一般写法
代码中的Connection的获取有很多种方式,不一定是代码中jdbcTemplate的方式,大家看的时候可以假设成其他的方式
public int insertOnePerson(String name, int age) { int result = 0; Connection conn = null; PreparedStatement pstmt = null; try { conn = jdbcTemplate.getDataSource().getConnection(); if(conn != null) { conn.setAutoCommit(false); pstmt = conn.prepareStatement(DELETE_ONE_PERSON); pstmt.setString(1, name); int count = pstmt.executeUpdate(); pstmt.close(); if(count >= 0) { pstmt = conn.prepareStatement(INSERT_ONE_PERSON); pstmt.setString(1, name); pstmt.setString(2, "1adh"); // 引发异常 result = pstmt.executeUpdate(); } conn.commit(); } } catch (SQLException e) { e.printStackTrace(); try { conn.rollback(); } catch (SQLException e1) { System.out.println("rollback failed.."); e1.printStackTrace(); } } finally { try{ conn.setAutoCommit(true); if(pstmt != null){ pstmt.close(); } if(conn != null){ conn.close(); } }catch(SQLException e){ } } return result ; }