JAVA PERSISTENCE API WIZARDS
7.1 PERFORM DATA MANIPULATIONS TO SQL SERVER DATABASE USING JPA WIZARDS
7.1.3 Perform Data Deleting to SQL Server Database Using
Basically, there is no signifi cant 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.
Figure 7.14. The updated faculty member.
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 identifi er 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 fi rst 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 tem- porarily reserve this current faculty name. Therefore, a local String variable cFaculty- Name 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 confi rm 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 transac- tion. 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.
Figure 7.15. The codes for the Delete button click event handler.
private void cmdDeleteActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here:
int numDeleted = 0;
String query = "DELETE FROM Faculty f WHERE f.facultyName=:FacultyName";
SelectQueryWizardPUEntityManager.clear();
facultyQuery = SelectQueryWizardPUEntityManager.createQuery(query);
facultyQuery.setParameter("FacultyName", ComboName.getSelectedItem());
String cFacultyName = (String)ComboName.getSelectedItem();
javax.persistence.EntityTransaction tr = SelectQueryWizardPUEntityManager.getTransaction();
if (!tr.isActive()){
tr.begin();
}
numDeleted = facultyQuery.executeUpdate();
tr.commit();
System.out.println("The number of deleted row is: " + numDeleted);
ComboName.removeItem(cFacultyName);
} A B C D E F G H
I J K L
c07.indd 479
c07.indd 479 7/20/2011 11:12:05 AM7/20/2011 11:12:05 AM
www.traintelco.com
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 fi nished developing the codes for this data deleting function.
To confi rm 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 confi rm 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 fi nd 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 confi rm 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 fi nally 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 fi nd 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 dele- tion. 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.
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
c07.indd 481
c07.indd 481 7/20/2011 11:12:05 AM7/20/2011 11:12:05 AM
www.traintelco.com
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.