After completing the basic architecture of database operations, it is time for us to perform JDBC data operations. The diagram of the involved database table Eris as follows:
As shown in, the first step is to add records to the t_user table. Because you need to operate multiple tables during user registration, you need to use transactions. First, write a simple JDBC-based transaction framework. The Code is as follows:
@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;}
The second is the specific user addition operation. The specific code is as follows:
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;}
Finally, the condition for successful judgment in the test case is changed to that the returned userId is greater than 0.
Run the test case. The test case should pass successfully.
After the above articles, we can finally carry out meaningful development work. The next step is to implement the business logic for all user registration. Another step is to handle abnormal situations, such as repeated usernames. After all these functions are completed, we also need to perform end-to-end testing, which involves registration testing through the JSP page.