Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Practical Database Programming With Java

.pdf
Скачиваний:
790
Добавлен:
10.06.2015
Размер:
31.58 Mб
Скачать

476 Chapter 7 Insert, Update, and Delete Data from Databases

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 file 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 file 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.Office: MTC-215

4.Phone: 750-378-1111

Figure 7.11. The updated faculty information.

7.1 Perform Data Manipulations to SQL Server Database Using JPA Wizards 477

5.College: Duke University

6.Email: sbai@college.com

Also, enter the name of a default faculty image file, Default.jpg, to the Faculty Image field, since we want to update this faculty’s image with this data updating. Your finished 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 find 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 find 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 confirm 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 first method, open the Services window in the NetBeans IDE and open our Faculty table. You can find that the faculty member Ying Bai has been updated, as shown in Figure 7.13.

Figure 7.12. A running successful message.

Figure 7.13. The updated faculty member Susan Bai.

478 Chapter 7 Insert, Update, and Delete Data from Databases

Figure 7.14. The updated faculty member.

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.

7.1.3 Perform Data Deleting to SQL Server Database Using JPA Wizards

Basically, there is no significant difference between the data updating and deleting using JPA wizards. In this section, we try to use the Delete button we built in the FacultyFrame form window before to perform this data deletion operation.

To make this deleting simple, we want to just delete the selected faculty record without touching the associated faculty image.

7.1.3.1 Develop the Codes for the Delete Button Event Handler

Launch the NetBeans IDE 6.8 and open the SelectQueryWizard project and the FacultyFrame form window. Double click on the Delete button to open its click event handler. Enter the codes that are shown in Figure 7.15 into this event handler.

7.1 Perform Data Manipulations to SQL Server Database Using JPA Wizards 479

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

Aint numDeleted = 0;

BString query = "DELETE FROM Faculty f WHERE f.facultyName=:FacultyName";

CSelectQueryWizardPUEntityManager.clear();

DfacultyQuery = SelectQueryWizardPUEntityManager.createQuery(query);

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

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

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

Hif (!tr.isActive()){

tr.begin();

}

InumDeleted = facultyQuery.executeUpdate();

Jtr.commit();

K

System.out.println("The number of deleted row is: " + numDeleted);

L

ComboName.removeItem(cFacultyName);

 

}

Figure 7.15. The codes for the Delete button click event handler.

Let’s have a closer look at this piece of codes to see how it works.

A.A local integer variable numDeleted is created and it is used to hold the number of the deleted rows when a data deleting is performed.

B.The query string with a JPQL identifier Delete is created. The point to be noted is that here we used the Java Persistence Query Language (JPQL) to perform this data deleting operation with the named parameter FacultyName as the query criterion.

C.The entity manager is first cleaned up to make it ready for our data deleting query.

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

E.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.

F.After this faculty record is deleted, the faculty name will be removed from the Faculty Name combo box later. In order to remember this deleted faculty name, we need to temporarily reserve this current faculty name. Therefore, a local String variable cFacultyName is created and used for this purpose.

G.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.

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

I.Now we can call the executeUpdate() method to perform this data deleting transaction. The execution result of this method is an integer that indicates the number of rows that have been deleted.

J.The commit()method is executed to trigger this data deleting operation.

480Chapter 7 Insert, Update, and Delete Data from Databases

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

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

At this point, we have finished developing the codes for this data deleting function. To confirm or validate this data deletion, we can still use the Select button, exactly the codes inside the Select button click event handler in this FacultyFrame form window.

Now let build and run our project to test and confirm this data deletion function.

7.1.3.2 Build and Run the Project to Test the Data Deletion

Make sure that our sample database CSE_DEPT has been connected to our 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.

Now 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.

To test this data deletion function, we can try to delete one faculty member, such as Ying Bai, from our Faculty table. To do that, select this faculty member from the Faculty Name combo box, and click on the Delete button. Immediately, you can find that this faculty name has been removed from the Faculty Name combo box. Also, the running result is shown in the Output window, as shown in Figure 7.16.

To confirm this data deletion, click on the Back and the Exit button to stop our project. Then open our Faculty table by going to the Services window and expand the Databases node, and our connection URL, and finally our sample database CSE_DEPT. Expand our database schema dbo and right click on the Faculty table. Select the View Data item from the pop-up menu to open our Faculty table. On the opened Faculty table, you can find that the faculty member Ying Bai has been removed from this table.

Our data deletion function is successful!

To make our database clean and neat, it is highly recommended to recover this deletion. The point to be noted is that when we delete a faculty member from the Faculty table, which is a parent table relative to the Course and LogIn tables that are child tables, the related records to that deleted faculty in those child tables will also be deleted since

Figure 7.16. The running result of the data deletion query.

7.1 Perform Data Manipulations to SQL Server Database Using JPA Wizards 481

a cascaded deleting relationship has been set up between the parent and child tables when we built this database in Chapter 2. Therefore, the faculty login record in the LogIn table and all courses taught by that faculty in the Course table will be deleted when the faculty member is deleted from the Faculty table. Also because the Course table is a parent table relative to the StudentCourse table, all courses taken by students and taught by the deleted faculty will be deleted from the StudentCourse table. To recover these deleted records, one needs to recover all of those deleted records related to the deleted faculty in those four tables. An easy way to do this recovery job is to use the Microsoft SQL Server Management Studio Express. For your convenience, we show these original records in Tables 7.2–7.5 again, and you can add or insert them back to those four tables to complete this data recovery.

Table 7.2. The deleted faculty record in the faculty table

faculty_id

faculty_name

office

phone

college

title

email

B78880

Ying Bai

MTC-211

750-378-1148

Florida Atlantic University

Associate Professor

ybai@college.edu

 

 

 

 

 

 

 

Table 7.3. The deleted course records in the course table

course_id

course

credit

classroom

schedule

enrollment

faculty_id

CSC-132B

Introduction to Programming

3

TC-302

T-H: 1:00-2:25 PM

21

B78880

CSC-234A

Data Structure & Algorithms

3

TC-302

M-W-F: 9:00-9:55 AM

25

B78880

CSE-434

Advanced Electronics Systems

3

TC-213

M-W-F: 1:00-1:55 PM

26

B78880

CSE-438

Advd Logic & Microprocessor

3

TC-213

M-W-F: 11:00-11:55 AM

35

B78880

 

 

 

 

 

 

 

Table 7.4. The deleted login records in the login table

user_name

pass_word

faculty_id

student_id

ybai

reback

B78880

 

 

 

 

 

Table 7.5. The deleted student course records in the studentcourse table

s_course_id

student_id

course_id

 

credit

major

1005

J77896

CSC-234A

3

CS/IS

1009

A78835

CSE-434

 

3

CE

1014

A78835

CSE-438

 

3

CE

1016

A97850

CSC-132B

 

3

ISE

1017

A97850

CSC-234A

 

3

ISE

482 Chapter 7 Insert, Update, and Delete Data from Databases

A complete sample project SelectQueryWizard that can be used to perform data insertion, updating, and deletion actions against our SQL Server sample database can be found from the folder DBProjects\Chapter 7 that is located at the Wiley ftp site (refer to Figure 1.2 in Chapter 1).

Next, let’s take care of the data manipulations against the Oracle database using the JPA Wizards.

7.2 PERFORM DATA MANIPULATIONS TO ORACLE DATABASE USING JPA WIZARDS

Generally, there is no significant difference between the data manipulations for the SQL Server and the Oracle databases. The only differences are the protocol of the query string used in the data manipulations and the mapped data table name. In the following sections, we will emphasize the different points between the protocols of these query strings.

First, let’s handle the data insertion query in the Oracle database.

7.2.1 Perform Data Insertion to Oracle Database Using JPA Wizards

To simplify this introduction, we can use a project OracleSelectWizard we developed in Section 6.2.9 in Chapter 6 and make some modifications to that project to make it as our new project. Perform the following operations to complete this project transferring:

1.Open the Windows Explorer and create a new folder, such as JavaDBProject\Chapter 7.

2.Open a Web browser and go to the folder DBProjects\Chapter 6 that is located at the Wiley ftp site (refer to Figure 1.2 in Chapter 1).

3.Copy the project OracleSelectWizard from that folder and paste it to our new folder

JavaDBProject\Chapter 7.

Now we are ready to build our data insertion query to perform data manipulations to our Oracle sample database CSE_DEPT.

In Section 6.2.7.1 in Chapter 6, we have created a FacultyFrame class and Faculty JFrame window FacultyFrame. Also, the following components have been added into that project:

The Faculty Entity Manager has been added into the FacultyFrame class.

The Oracle sample database has been connected to our project.

In this section, we want to use the Insert button that has been added into the FacultyFrame window to perform this data insertion function.

7.2.1.1 Modify the FacultyFrame Window Form

First, let’s modify the FacultyFrame form by adding three more Text Fields into this frame: two of them are added into the Faculty Information panel to enable us to insert a faculty record, and one them is added at the top of the faculty image box to allow us to insert a new faculty image (exactly the location of the faculty image).

7.2 Perform Data Manipulations to Oracle Database Using JPA Wizards 483

Perform the following operations to open our pasted project OracleSelectWizard:

1.Launch the NetBeans IDE 6.8 and go to File > Open Project menu item to open the Open Project wizard.

2.Browse to the location where we copied and pasted our project OracleSelectWizard, which is JavaDBProject\Chapter 7. Make sure that the Open as Main Project checkbox has been checked, and select this project and click on the Open Project button to open it.

The point to be noted is that you now have two OracleSelectWizard projects in the NetBeans IDE, but they are different projects with different functions. The first OracleSelectWizard was built in Chapter 6 without data manipulation function, but this second project will be built in Chapter 7 with the data manipulation function.

3.Expand this project files to open the FacultyFrame.java file by double clicking on this file that is located under the Source Packages\LogInFramePackage node.

4.Click on the Design button at the top of this window to open the GUI window of this FacultyFrame class.

Perform the following operations to add three more Text Fields into this frame window:

• Enlarge the FacultyFrame window form and the Faculty Information panel.

• Add two more labels and two more Text fields into this Faculty Information panel, and one more label and the associated Text Field to the top of the Faculty Image box with the properties shown in Table 7.6.

One point to be noted is the FacultyIDField, and its editable property is checked, which means that we want users to insert a new faculty_id as the project runs. However, this property should not be checked when we perform a data updating action because we will not update a faculty_id during a faculty record updating process.

Your finished modified FacultyFrame form window should match one that is shown in Figure 7.17.

Now let’s develop the codes for the Insert button click event handler to perform the data insertion function as the project runs. As we did for the SQL Server database, we will use the JPQL persist() method to perform this data insertion.

7.2.1.2 Develop the Codes for the Insert Button Event Handler

As we mentioned, there is no significant difference in querying a SQL Server and an Oracle database using JPAWizard in NetBeans 6.8.The whole project SelectQueryWizard

Table 7.6. Objects and controls added into the faculty frame window

Type

Variable Name

Text

editable

Title

Label

Label1

Faculty ID

 

 

Text Field

FacultyIDField

 

checked

 

Label

Label2

Name

 

 

Text Field

FacultyNameField

 

checked

 

Label

Label3

Faculty Image

 

 

Text Field

FacultyImageField

 

checked

 

484 Chapter 7 Insert, Update, and Delete Data from Databases

Figure 7.17. The modified FacultyFrame form window.

we built in Chapter 6 can be used to perform data manipulations to an Oracle database with a little modification. Exactly you can copy the codes in the Insert button click event handler we built in Section 7.1.1.3 and paste them into the Insert button click event handler in the FacultyFrame form in our current OracleSelectWizard project.

Four small modifications are important and necessary, and they are listed below:

1.The data table name used in the query strings. There is a little difference for the table names used in SQL Server database and Oracle database in the JPA mapped Entity classes. For example, the LogIn table in our sample SQL Server database CSE_DEPT is still mapped to LogIn in the LogIn.java Entity class; however, it is mapped to Login in the Login.java Entity class for the Oracle database. Make sure to check the Entity classes to confirm and use the correct table names when different databases are utilized.

2.The query components used in the data query operations. These is little difference in the names of the JPA query components used in SQL Server database and Oracle database when they are added into each Frame Form window. For example, the LogIn JPA query object used in SQL Server database is named logInQuery; however, it is named loginQuery when is created for the Oracle database. Make sure to check the added query components to confirm and use the correct query components for each Frame.

3.The entity manager class name used in the Oracle database is different with that in the SQL Server database. In the project OracleSelectWizard, the name of the mapped entity manager class is OracleSelectWizardPUEntityManager; therefore, you need to use this name to replace the SelectQueryWizardPUEntityManager, which is the name of the mapped entity manager for the SQL Server database, in all codes to perform a data manipulation to our Oracle sample database.

7.2 Perform Data Manipulations to Oracle Database Using JPA Wizards 485

4.The ShowFaculty() method should be modified and divided into two submethods, ShowFaculty() and DisplayImage(), to coordinate the data manipulations. Refer to Section 7.1.1.4 to complete this modification.

One point to be remembered is that you can copy the codes from the Select button click event handler from the project SelectQueryWizard and paste them into the Select button click event handler in the FacultyFrame form in our current OracleSelectWizard project to perform the validation of this data insertion. The only modification is to replace the SQL Server entity manager SelectQueryWizardPUEntityManager with the Oracle entity manager OracleSelectWizardPUEntityManager in that piece of codes.

Another point to be noted is that you need to copy all image files, including both faculty and student image files, from the Image folder that is located at the site ftp:// ftp.wiley.isbn/JavaDB, and paste them to your current project folder. In this case, it should be JavaDBProject\Chapter 7\OracleSelectWizard. You need also to remember to connect to our sample Oracle database we loaded in Section 6.2.1.3 when you create Entity classes for each tables in that Oracle database. Follow steps listed below to complete this database connection and mapping:

1.Click on the Services tab to open the Services window

2.Extend the Databases node and you can find our load-in Oracle sample database jdbc:oracle:thin:@localhost:1251:XE [CSE_DEPT on CSE_DEPT]

3.Right click on that load-in database node and select the Connect item from the pop-up menu to connect to this sample database

Now you can perform data insertion actions against our Oracle database. In order to keep our database clean and neat, it is highly recommended to delete this new inserted faculty record from our sample database after you finished this data insertion testing.

A complete sample project OracleSelectWizard that can be used to perform data insertion actions against Oracle Database 10g XE can be found from the folder DBProjects\ Chapter 7 that is located at the Wiley ftp site (refer to Figure 1.2 in Chapter 1).

Next, let’s develop the codes to perform data updating actions against our Oracle database.

7.2.2 Perform Data Updating to Oracle Database Using JPA Wizards

Generally there is no difference between update data against a SQL Server and an Oracle database, and we can use almost all codes we developed in the Update button click event handler in Section 7.1.2.1 to perform a data updating action against our Oracle database. Therefore, you can copy those codes and paste them into the Update button click event handler in the FcaultyFrame form in our current OracleSelectWizard project.

The only point to be noted is that the FacultyIDField should be disabled since we do not want to update a faculty_id when we update a faculty record. Refer to Section 7.1.2 to get more details about the reason for this point.

To disable the faculty_id to be modified during a data updating action, open the Update button click event handler and add the codes that are shown in Figure 7.18 into this handler. The newly added codes have been highlighted in bold.

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]