spring 对 JdbcTemplate……的事务管理不用担心。就是对直接Jdbc实现的Dao事务管理有点小问题,如:我直接,用dataSource.getConnection()。spring是管理不了事务的。原因是Jdbc实现的Dao里的connection是自动提交的。要改用经过spring 处理过的connection = DataSourceUtil.getConnection(dataSource);才行。
我这有个例子——用户注册,有备份。只是例子而且。
下面是原始的Dao实现,
备份方法:
public
User backUp(User user)
throws
SQLException {
Connection conn = dataSource.getConnection();
try {
PreparedStatement pstmt = conn.prepareStatement( " insert into user(name) values (?) " );
pstmt.setString( 1 , user.getName() + " 备份 " );
pstmt.executeUpdate();
pstmt = conn.prepareStatement( " select last_insert_id() " );
ResultSet rs = pstmt.executeQuery();
if (rs != null && rs.next()) {
user.setUId(rs.getInt( 1 ));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
throw e;
} finally {
if (conn != null ) {
try {
conn.close();
} catch (SQLException e) {
System.out.println( " 数据库连接关闭失败! " );
}
}
}
return user;
}
Connection conn = dataSource.getConnection();
try {
PreparedStatement pstmt = conn.prepareStatement( " insert into user(name) values (?) " );
pstmt.setString( 1 , user.getName() + " 备份 " );
pstmt.executeUpdate();
pstmt = conn.prepareStatement( " select last_insert_id() " );
ResultSet rs = pstmt.executeQuery();
if (rs != null && rs.next()) {
user.setUId(rs.getInt( 1 ));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
throw e;
} finally {
if (conn != null ) {
try {
conn.close();
} catch (SQLException e) {
System.out.println( " 数据库连接关闭失败! " );
}
}
}
return user;
}
现在要改成:
public
User backUp(User user)
throws
SQLException {
Connection conn = DataSourceUtils.getConnection(dataSource);
try {
PreparedStatement pstmt = conn.prepareStatement( " insert into user(name) values (?) " );
pstmt.setString( 1 , user.getName() + " 备份 " );
pstmt.executeUpdate();
pstmt = conn.prepareStatement( " select last_insert_id() " );
ResultSet rs = pstmt.executeQuery();
if (rs != null && rs.next()) {
user.setUId(rs.getInt( 1 ));
}
} catch (SQLException e) {
throw e;
} finally {
DataSourceUtils.releaseConnection(conn, dataSource);
}
return user;
}
Connection conn = DataSourceUtils.getConnection(dataSource);
try {
PreparedStatement pstmt = conn.prepareStatement( " insert into user(name) values (?) " );
pstmt.setString( 1 , user.getName() + " 备份 " );
pstmt.executeUpdate();
pstmt = conn.prepareStatement( " select last_insert_id() " );
ResultSet rs = pstmt.executeQuery();
if (rs != null && rs.next()) {
user.setUId(rs.getInt( 1 ));
}
} catch (SQLException e) {
throw e;
} finally {
DataSourceUtils.releaseConnection(conn, dataSource);
}
return user;
}
然后你在逻辑层就可以用spring的任何方式管理事务了。
如:注册
public
User register(User user)
throws
SQLException {
userDao.backUp(user);
userDao.insert(user);
return user;
}
userDao.backUp(user);
userDao.insert(user);
return user;
}