spring 對(duì) JdbcTemplate……的事務(wù)管理不用擔(dān)心。就是對(duì)直接Jdbc實(shí)現(xiàn)的Dao事務(wù)管理有點(diǎn)小問題,如:我直接,用dataSource.getConnection()。spring是管理不了事務(wù)的。原因是Jdbc實(shí)現(xiàn)的Dao里的connection是自動(dòng)提交的。要改用經(jīng)過spring 處理過的connection = DataSourceUtil.getConnection(dataSource);才行。
我這有個(gè)例子——用戶注冊(cè),有備份。只是例子而且。
下面是原始的Dao實(shí)現(xiàn),
備份方法:
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("數(shù)據(jù)庫(kù)連接關(guān)閉失敗!");
}
}
}
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("數(shù)據(jù)庫(kù)連接關(guān)閉失敗!");
}
}
}
return user;
}
現(xiàn)在要改成:
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的任何方式管理事務(wù)了。
如:注冊(cè)
public User register(User user) throws SQLException {
userDao.backUp(user);
userDao.insert(user);
return user;
}
userDao.backUp(user);
userDao.insert(user);
return user;
}