Perform Data Updating to SQL Server Database Using

Một phần của tài liệu practical database aprogramming with java (Trang 349 - 353)

JAVA PERSISTENCE API WIZARDS

7.1 PERFORM DATA MANIPULATIONS TO SQL SERVER DATABASE USING JPA WIZARDS

7.1.2 Perform Data Updating to SQL Server Database Using

Regularly, we do not need to update a faculty_id when we update a faculty record since a better way to do that is to insert a new faculty record and delete the old one. The main reason for this is that a very complicated operation would be performed if the faculty_id were updated since it is a primary key in the Faculty table and foreign keys in the

Course and the LogIn tables. To update a primary key, one needs to update foreign keys fi rst in the child tables and then update the primary key in the parent table. This will make our updating operation very complicated and easy to be confused. In order to avoid this confusion, in this sec tion, we will update a faculty record by changing any column except the faculty_id , and this is a popular way to update a table and widely implemented in most database applications.

7.1.2.1 Develop the Codes for the Update Button Event Handler

We want to use the Update button we built in this FacultyFrame form window to perform a faculty updating function; therefore, no modifi cation to this FacultyFrame form window to be made. Now let ’ s develop the codes for the Update button click event handler.

Open this event handler and enter the codes that are shown in Figure 7.10 into this event handler. Let ’ s have a closer look at this piece of codes to see how it works.

A. A local integer variable numUpdated is created, and it is used to hold the number of the updated rows when a data updating is performed.

B. The query string with a JPQL identifi er Update is created. The point to be noted is that here we used the Java Persistence Query Language ( JPQL ) to perform this data updating operation with the position holder as the positional parameters. The facultyName , which is a query criterion and followed the WHERE clause, is a named parameter. Refer to Section 6.2.5.4 in Chapter 6 to get a more detailed discussion about the positional and named parameters for a JPQL query. If you like, you can use the named parameters to replace those positional parameters, such as f.facultyName = :fname, f.title = : ftitle , and so on.

C. The entity manager is fi rst cleaned up to make it ready for our query.

D. A new updating query is created by executing the createQuery() method with the query string as the argument.

E. Six positional parameters involved in this updating query are initialized by using the set- Parameter() method. The input or argument for these methods are obtained by calling the getText() method of each associated Text Field object. The point to be noted is that the order of these positional parameters in these setParameter() methods must match to the order number in the query string.

F. The query criterion, which is the selected faculty name from the Faculty Name combo box, is a named parameter. So this parameter is initialized with the named parameter format.

G. After this faculty record is updated, the current faculty name may also be updated. In order to update the Faculty Name combo box, we need to temporarily reserve this current faculty name. Therefore, a local String variable cFacultyName is created and used for this purpose.

H. A new Transaction Association instance is created by calling the getTransaction() method. Since this Transaction class is located at the javax.persistence package, so a full name is used here for this class. As we mentioned, unlike the data query, such as SELECT statement, all data manipulation queries, such as UPDATE and DELETE , must be under the control of a Transaction instance.

I. Before we can start this Transaction instance, we need to confi rm whether this Transaction Association has been active. Then we can start it using the begin() method if this Transaction instance is inactive.

J. Now we can call the executeUpdate() method to perform this data updating transac- tion. The execution result of this method is an integer that indicates the number of rows that have been updated.

K. The commit() method is executed to trigger this data updating operation.

L. The execution result is printed out as a debug purpose.

M. The new updated faculty name stored in the FacultyNameField is added into the Faculty Name combo box to update that object and enable us to do the validation of this data updating later.

N. The current or old faculty name is removed from the Faculty Name combo box.

Figure 7.10. The developed codes for the Update button click event handler.

private void cmdUpdateActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here:

int numUpdated = 0;

String query = "UPDATE Faculty f SET f.facultyName=?1, f.title=?2, f.office=?3, f.phone=?4, " + "f.college=?5, f.email=?6 WHERE f.facultyName=:FacultyName";

SelectQueryWizardPUEntityManager.clear();

facultyQuery = SelectQueryWizardPUEntityManager.createQuery(query);

facultyQuery.setParameter(1, FacultyNameField.getText());

facultyQuery.setParameter(2, TitleField.getText());

facultyQuery.setParameter(3, OfficeField.getText());

facultyQuery.setParameter(4, PhoneField.getText());

facultyQuery.setParameter(5, CollegeField.getText());

facultyQuery.setParameter(6, EmailField.getText());

facultyQuery.setParameter("FacultyName", ComboName.getSelectedItem());

// reserve the current faculty name

String cFacultyName = (String)ComboName.getSelectedItem();

javax.persistence.EntityTransaction tr = SelectQueryWizardPUEntityManager.getTransaction();

if (!tr.isActive()){

tr.begin();

}

numUpdated = facultyQuery.executeUpdate();

tr.commit();

System.out.println("The number of updated row is: " + numUpdated);

ComboName.addItem(FacultyNameField.getText());

ComboName.removeItem(cFacultyName);

} A

B C D E

F G H I

J K L M N

c07.indd 475

c07.indd 475 7/20/2011 11:12:03 AM7/20/2011 11:12:03 AM

www.traintelco.com

Figure 7.11. The updated faculty information.

For the validation of this data updating, we can use the same codes we developed in Section 7.1.1.4 .

Now let ’ s build and run our project to test its data updating function. Make sure that a default faculty image fi le Default.jpg has been saved to our project folder in this application, which is C:\JavaDBProject\Chapter 7\SelectQueryWizard . Of course, you do not need this image fi le if you do not want to update any faculty image when you perform a faculty updating.

7.1.2.2 Build and Run the Project to Test the Data Updating Before you can run this project, the following conditions have to be met:

䊏 The SQL Server sample database CSE_DEPT has been connected to this project. To check this connection, open the Services window and expand the Databases node to locate our sample database connection URL, jdbc:sqlserver://localhost\SQL2008EXPRESS:

5000;databaseName=CSE_DEPT [ybai on dbo] . Right click on this URL and select the Connect item to do this connection.

Click on the Clean and Build Main Project button from the toolbar to build our project. Then click on the Run Main Project button to run the project.

Enter a suitable username and password, such as jhenry and test , to complete the login process and select the Faculty Information from the SelectFrame window to open the FacultyFrame window. The default faculty information is displayed.

Enter the following information into six Text Fields (no Faculty ID Text Field) inside the Faculty Information panel as an updated faculty record, as shown in Figure 7.11 .

1. Name: Susan Bai 2. Title: Professor 3. Offi ce: MTC - 215 4. Phone: 750 - 378 - 1111

Figure 7.12. A running successful message.

Figure 7.13. The updated faculty member Susan Bai.

Also, enter the name of a default faculty image fi le, Default.jpg , to the Faculty Image fi eld, since we want to update this faculty ’ s image with this data updating. Your fi nished updating window should match one that is shown in Figure 7.11 .

Click on the Update button to perform this data updating. Immediately, you can fi nd that the updated faculty name Susan Bai has been added into the Faculty Name combo box, and the original faculty member Ying Bai has been removed from this box when clicking on the drop down arrow of that box.

To test this data updating, open the Output window if it has not been opened.

You can fi nd that a running successful message is displayed in that window, as shown in Figure 7.12 .

Similar to the data insertion operation, here we have two ways to validate this data updating. One way is to open our Faculty table to confi rm this data updating, and the other way is to use the Select button (exactly the codes inside that button ’ s click event handler) to do this validation.

To use the fi rst method, open the Services window in the NetBeans IDE and open our Faculty table. You can fi nd that the faculty member Ying Bai has been updated, as shown in Figure 7.13 .

5. College: Duke University 6. Email: sbai@college.com

c07.indd 477

c07.indd 477 7/20/2011 11:12:04 AM7/20/2011 11:12:04 AM

www.traintelco.com

To use the second way to do this data updating validation, select the updated faculty member Susan Bai from the Faculty Name combo box and click on the Select button to try to retrieve this updated faculty record from our sample database.

The retrieved updated faculty information is shown in Figure 7.14 . Click on the Back and the Exit buttons to terminate our project.

Our data updating function is successful! It is highly recommended to recover the updated faculty record in the Faculty table since we want to keep our sample database clean and neat. You can do that recovery job by using the Microsoft SQL Server Management Studio Express. To open that Studio Express, go to Start\All Programs\

Microsoft SQL Server 2008\SQL Server Management Studio .

Next, let ’ s take care of the data deletion from our sample database using the JPA wizard.

Một phần của tài liệu practical database aprogramming with java (Trang 349 - 353)

Tải bản đầy đủ (PDF)

(791 trang)