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;
}
現在要改成:
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;
}
然后你在邏輯層就可以用spring的任何方式管理事務了。
如:注冊
public User register(User user) throws SQLException {
userDao.backUp(user);
userDao.insert(user);
return user;
}
posted on 2007-08-20 11:22
流浪汗 閱讀(653)
評論(0) 編輯 收藏 所屬分類:
Spring