完成資料庫操作的基礎架構之後,就是我們真正進行JDBC資料操作的時候了。所涉及的資料庫表ER圖如下所示:
如所示,我們第一步是向t_user表中添加記錄。由於使用者註冊需要操作多張表,因此需要用到事務,先寫出一個簡單的基於JDBC的事務架構,代碼如下所示:
@Overridepublic long registerUser(Map<String, Object> userInfo) {Connection conn = null;long userId = 0;try {conn = JdbcDs.getConnection();conn.setAutoCommit(false);userId = addUser(conn, userInfo);if (userId <= 0) {throw new SQLException("Fail to add user in t_user");}conn.commit();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();try {conn.rollback();} catch (SQLException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}userId = -1;} finally {try {conn.close();} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}}return userId;}
其次是具體的使用者添加操作,具體代碼如下所示:
private long addUser(Connection conn, Map<String, Object> userInfo) {long userId = -1;PreparedStatement stmt = null;ResultSet rst = null;String sql = "insert into t_user(user_name, user_group_id, user_level_id) values(?, 2, 1)";try {stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);stmt.setString(1, (String)userInfo.get("userName"));int affectedNum = stmt.executeUpdate();if (1 == affectedNum) {rst = stmt.getGeneratedKeys();if (rst.next()) {userId = rst.getLong(1);}} else {userId = -1;}} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();userId = -1;} finally {try {if (rst != null) {rst.close();}if (stmt != null) {stmt.close();}} catch (Exception ex) {}}return userId;}
最後是改變測試案例中的判斷成功條件為所返回的userId大於0。
運行測試案例,應該可以成功通過測試案例。
經過以上幾篇文章,我們終於可以進行有意義的開發工作了。下一步就是實現所有使用者註冊商務邏輯,還有一塊是異常情況的處理,例如userName重複的情況。當完成所有這些功能後,我們還需要進行端到端測試,這就涉及通過JSP頁面進行註冊測試。