After completing the infrastructure for database operations, it is time for us to actually perform JDBC data operations. The ER diagram of the database table involved is as follows:
As shown in the figure above, our first step is to add records to the t_user table. Since user registration requires operating multiple tables, transactions need to be used. First, write a simple JDBC-based transaction framework. The code is as follows:
@Override public 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 block e.printStackTrace(); try { conn.rollback(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } userId = -1; } finally { try { conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return userId; }
The second is the specific user addition operation. The specific code is as follows As shown:
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 block e.printStackTrace(); userId = -1; } finally { try { if (rst != null) { rst.close(); } if (stmt != null) { stmt.close(); } } catch (Exception ex) { } } return userId; }
Finally, change the success condition in the test case to the returned userId greater than 0.
Run the test case and the test case should pass successfully.
After the above articles, we can finally carry out meaningful development work. The next step is to implement all user registration business logic, and another step is to handle abnormal situations, such as repeated userName. After completing all these functions, we also need to conduct end-to-end testing, which involves registration testing through JSP pages.
The above is the content of the New Java Movement: Test Driven Development 3---User Registration 4. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!