7 従業員レコードの更新
更新機能は、Webページでのユーザーの編集に応じて、データベース内の従業員レコードを変更します。
まず、レコード内の従業員を検索する必要があります。従業員に関連する情報を取得すると、従業員に関連する詳細を変更するための「編集」ボタンが表示されます。
この章では、更新機能の作成に必要なコードの追加について学習します。次の方法について学習します。
JavaBean.java
で新しいメソッドgetEmployeeByFn(String)
を宣言します。JavaBean.java
で新しいメソッドupdateEmployee(int)
を宣言します。- 新しいメソッド
getEmployeeByFn(String)
をJavaBeanImpl.java
で実装します。 - 新しいメソッド
updateEmployee(int)
をJavaBeanImpl.java
で実装します。 - 新しいコードを
WebController.java
に追加して、リクエストとレスポンスを処理します。 - HTMLページ
listByName.html
を作成して、結果を表示します。
ノート:
hradminユーザーには、従業員レコードを更新する権限があります。hrstaffユーザーには、従業員レコードを更新する権限がありません。EmployeeBean.javaでの新しいメソッドgetEmployeeByFn(String)の宣言
従業員の詳細を変更するには、hradminは最初に名で従業員を検索する必要があります。getEmployeeByFn(String)
メソッドは、名に基づいて従業員を検索します。
クラス名: src/main/java/com/oracle/jdbc/samples/bean/EmployeeBean.java
Githubの場所: EmployeeBean.java
新しいメソッドを宣言するステップ:
- IntelliJで
JdbcBean.java
ファイルを開きます。JdbcBean.javaクラスを作成するには、JDBC接続のためのJava Beanインタフェースの作成を参照してください。同じクラスを使用し、各機能に対して新しいメソッドを宣言します。 - 入力パラメータとして名を取るメソッド
getEmployeeByFn(String)
を宣言します。public List<Employee> getEmployeeByFn(String fn);
新しいメソッドupdateEmployee(Employee)の宣言
updateEmployee(Employee)
メソッドは、名、姓、給与、job_idなどの従業員の属性を更新します。
クラス名: src/main/java/com/oracle/jdbc/samples/bean/JavaBean.java
.
Githubの場所: EmployeeBean.java
新しいメソッドを宣言するステップ:
- IntelliJで
JdbcBean.java
ファイルを開きます。JdbcBean.javaクラスを作成するには、JDBC接続のためのJava Beanインタフェースの作成を参照してください。同じクラスを使用し、各機能に対して新しいメソッドを宣言します。 - Employeeオブジェクトを入力パラメータとして取るメソッド
updateEmployee(Employee)
を宣言します。public Employee updateEmployee(int empId);
従業員名による検索のための新しいメソッドgetEmployeebyFn()
の実装
getEmployeeByFn(String)
メソッドは、従業員IDを入力パラメータとして取り、Employee型のオブジェクトを返します。
クラス名: src/main/java/com/oracle/jdbc/samples/bean/JdbcBeanImpl.java
Githubの場所: EmployeeBeanImpl.java
メソッドを実装するステップ:
- IntelliJで
JdbcBeanImpl.java
ファイルを開きます。JdbcBeanImpl.java
クラスを作成するには、JDBC接続のためのJava Bean実装の作成を参照してください。同じクラスを使用し、各機能に対して新しい実装メソッドを追加します。 - 次のコード・スニペットを追加して、
getEmployeeByFn(String)
メソッドを実装します。public List<Employee> getEmployeeByFn(String fn) { /* Declare an array to store the returned employee list */ List<Employee> returnValue = new ArrayList<>(); /* Get the database connection */ try (Connection connection = getConnection()) { /* Insert the SQL statement to fetch an employee using the employee first name */ try (PreparedStatement preparedStatement = connection.prepareStatement( "SELECT Employee_Id, First_Name, Last_Name, Email, Phone_Number, Job_Id, Salary FROM EMPLOYEES WHERE First_Name LIKE ?")) { /* Set the input parameter as the first name */ preparedStatement.setString(1, fn + '%'); try (ResultSet resultSet = preparedStatement.executeQuery()) { while(resultSet.next()) { /* Check if the resultSet has any value */ returnValue.add(new Employee(resultSet)); } } } } catch (SQLException ex) { /* Catch the SQLException and log the message in logger*/ logger.log(Level.SEVERE, null, ex); ex.printStackTrace(); } /* Return the list of employees from the method */ return returnValue; }
新しいメソッドupdateEmployee(Employee)の実装
updateEmployee(Employee)
メソッドを使用すると、従業員レコードのfirst_nameやlast_nameなどの従業員の詳細を更新できます。
クラス名: src/main/java/com/oracle/jdbc/samples/bean/EmployeeBeanImpl.java
Githubの場所: EmployeeBeanImpl.java
新しいメソッドを実装するステップ:
- IntelliJで
JdbcBeanImpl.java
ファイルを開きます。JdbcBeanImpl.java
クラスを作成するには、JDBC接続のためのJava Bean実装の作成を参照してください。同じクラスを使用し、各機能に対して新しい実装メソッドを追加します。 - 次のコード・スニペットを追加して、
updateEmployee(Employee)
メソッドを実装します。public String updateEmployee(Employee employee) throws SQLException { /*Declare and initialize a variable to capture the number of records updated*/ int updateCount = 0; /* Get the database connection*/ try (Connection connection = getConnection()) { try (PreparedStatement preparedStatement = connection.prepareStatement( /* Insert the SQL statement to select an employee based on the employee id */ "UPDATE employees SET FIRST_NAME = ?, LAST_NAME = ?, EMAIL = ?, PHONE_NUMBER = ?, SALARY = ? WHERE EMPLOYEE_ID = ?")) { /*Set the new values entered by the user for each attribute and execute the prepapredStatement */ preparedStatement.setString(1, employee.getFirst_Name()); preparedStatement.setString(2, employee.getLast_Name()); preparedStatement.setString(3, employee.getEmail()); preparedStatement.setString(4, employee.getPhone_Number()); preparedStatement.setInt(5, employee.getSalary()); preparedStatement.setInt(6, employee.getEmployee_Id()); updateCount = preparedStatement.executeUpdate(); } }catch (SQLException ex) { /* Catch the SQLException and log the message in the logger*/ logger.log(Level.SEVERE, "Unable to update record", ex); throw new SQLException("Alert! Record could not be updated, "+ex.getMessage(), ex); } /* Log the message with the number of records updated to the logger */ logger.fine("Update count: " +updateCount); /* If none of the records were updated, enter an alert message */ if (updateCount != 1) { logger.severe("Unable to update record"); throw new SQLException("Alert! Record could not be updated"); } /* Return the success message if the record was updated */ return "Success: Record updated"; }
リクエストを処理するコードのサーブレットへの追加
従業員を更新するための関連コードをWebController.java
に追加します。
クラス名: src/main/java/com/oracle/jdbc/samples/web/WebController.java
Githubの場所: WebController.java
コードを追加するステップ:
WebController.java
クラスを開きます。WebController.java
を作成するには、リクエストを処理するサーブレットの作成を参照してください。同じクラスを使用して、必要なコードを追加します。- 従業員の名を取得する変数
FN_KEY
を宣言します。これはグローバル変数であるため、processRequest()
メソッドの外部で、ただしWebController
クラスの内部で宣言します。private static final String FN_KEY = "firstName";
- メソッド
processRequest()
は、ListAll機能ですでに作成されています。次に、従業員の更新機能を実装するコードを追加します。新しい機能を処理するELSEIF条件を追加します。ユーザーが入力した従業員IDを取得し、メソッドgetEmployee(int)
を起動して従業員レコードが存在するかどうかを確認します。if ((value = request.getParameter(ID_KEY)) != null) { int empId = Integer.valueOf(value).intValue(); employeeList = employeeBean.getEmployee(empId); } /* New code added below */ else if ((value = request.getParameter(FN_KEY)) != null) { employeeList = jdbcBean.getEmployeeByFn(value); } else { /* Previously used getEmployees() method for Listall feature */ employeeList = employeeBean.getEmployees(); }
従業員IDによる検索のための新規HTMLの作成
ユーザーが従業員の名を入力するための入力プレースホルダを示すHTMLページ。従業員レコードが見つかった場合は、従業員の詳細がページに表示され、それ以外の場合はエラー・メッセージが表示されます。
クラス名:src/main/webapp/listById.html
Githubの場所: listByName.html
HTMLページを作成するステップ:
- HTMLページのtitle、stylesheetおよびbodyを作成します。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>List Employee by Id</title> <!-- Specify the stylesheet here --> <link rel="stylesheet" type="text/css" href="css/app.css" > <!-- Bootstrap JS for the UI --> <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script> </head>
- 従業員IDを取得するための
<body>
タグと<input>
タグを開始します。<body> <div><label>Employee First Name: </label> <input id="firstName" type="textfield" onkeypress="return waitForEnter(event)"\> wildcard % is included at the end automatically.</div> <br/> <br/> <div id="id-emp"></div> <div id="UpdateButton"> <button type="button" class="btn btn-info btn-lg" onclick='javascipt:confirmUpdate()'>Update Record</button> <button type="button" class="btn btn-default btn-lg" onclick='javascipt:cancelUpdate()'>Cancel</button> </div>
- リクエストの送信時、つまりいずれかの機能のリンクが選択されたときのアクションを定義します。
$('#UpdateButton').hide(); // keys; function waitForEnter(e) { if (e.keyCode == 13) { fetchElement($("#firstName").val()); return false; } } function fetchElement(firstName) { var xmlhttp = new XMLHttpRequest(); var url = "WebController?firstName=" +firstName; xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { processResponse(xmlhttp.responseText); } } xmlhttp.open("GET", url, true); xmlhttp.send(); }
- HTMLページにJSON結果を表示する
processResponse()
関数を作成します。function processResponse(response) { var arr = JSON.parse(response); if (arr == null || arr.length == 0) { out = '<div class="alert alert-warning"><strong>Alert!</strong>' +' No records found for the given Fist_Name</div>' } else { var i; var out = "<table>"; // keys is global so that it can be used later as well keys = Object.keys(arr[0]); // Print headers out += "<tr><th>Trash</th><th>Edit</th>" for(i = 0; i < keys.length; ++i) { out += "<th>"+keys[i]+"</th>" } out += "</tr>"; // Print values for(j = 0; j < arr.length; j++) { pk = arr[j][keys[0]]; out += '<tr><td><a href="javascript:confirmDelete(\'' +pk +'\')">' +'<span class="glyphicon glyphicon-trash"></span>' +'</a></td>' +'<td><a href="javascript:allowEditSalary(\'' +pk +'\')">' +'<span class="glyphicon glyphicon-edit"></span>' +'</a></td>'; // 0 is the primary key for(i = 0; i < keys.length; ++i) { // creating an id to each column out += "<td id='" +pk +'_' +keys[i] +"'> "+arr[j][keys[i]]+"</td>"; } out += "</tr>" } out += "</table>"; } $('#id-emp').html(out); }
- allowEditSalary(pk)関数を追加して、従業員レコードの表示後にフィールド名を編集可能にします。
function allowEditSalary(pk) { // If the edit button is pressed already if(typeof currentPK != 'undefined' && currentPK == pk) { console.log('Make column readonly'); for(i = 1; i < keys.length; ++i) { var x = '#' +pk +"_" +keys[i]; var value = $(x).text().trim(); console.log(value); $(x).val(value); } $('#UpdateButton').hide(); currentPK = ''; } else{ currentPK = pk; for(i = 1; i < keys.length; ++i) { var x = '#' +pk +"_" +keys[i]; var value = $(x).text().trim(); $(x).html("<input type='text' value='" +value +"' \>"); } $('#UpdateButton').show(); } }
confirmUpdate()
関数とcancelUpdate()
関数を追加して、それぞれ確認アクションと取消しアクションを定義します。function confirmUpdate() { var res = confirm("Do you really want to Update"); if(res == true) { console.log("Udating record"); $('#UpdateButton').hide(); } else { console.log("Record not updated"); } } function cancelUpdate() { if(typeof currentPK != 'undefined') { console.log('Make column readonly'); for(i = 1; i < keys.length; ++i) { var x = '#' +pk +"_" +keys[i]; var value = $(x).text().trim(); console.log("cancelUpdate: " +value); $(x).text(value); } $('#UpdateButton').hide(); currentPK = ''; } }