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

Practical Database Programming With Java

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

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

Figure 7.1. The modified FacultyFrame form window.

One point to be noted is the FacultyIDField, and its editable property is unchecked, which means that we do not want users to modify the faculty_id as the project runs because we will not update it during a faculty record updating process.

Your finished modified FacultyFrame form window is shown in Figure 7.1.

Now let’s develop the codes for the Insert button click event handler to perform the data insertion function as the project runs. Before we can do that, first, let’s take a closer look at the persist tool since the JPQL did not provide a direct Insert command, and therefore we have to use this tool to perform the data insertion function.

7.1.1.2 The Persist Method in the EntityManager Class

Persist is a Java-based Object Relational Mapping (ORM) and Data Access Object

(DAO) tool. It provides only the minimal amount of functionalities necessary to map objects or maps from database queries and to statement parameters.

An EntityManager instance is associated with a persistence context. A persistence context is a set of entity instances in which for any persistent entity identity there is a unique entity instance. Within the persistence context, the entity instances and their lifecycle are managed. The EntityManager interface defines the methods that are used to interact with the persistence context. The EntityManager API is used to create and remove persistent entity instances, to find entities by their primary key, and to query over entities.

The set of entities that can be managed by a given EntityManager instance is defined by a persistence unit. A persistence unit defines the set of all classes that are related or grouped by the application, and which must be co-located in their mapping to a single database.

The EntityManager is the primary interface used by application developers to interact with the JPA runtime. The methods of the EntityManager can be divided into the following functional categories:

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

Transaction Association

Every EntityManager has a one-to-one relation with an EntityTransaction instance. In fact, many vendors use a single class to implement both the EntityManager and EntityTransaction interfaces. If an application requires multiple concurrent transactions, one will use multiple EntityManagers.

One can retrieve the EntityTransaction associated with an EntityManager through the getTransaction() method. Note that most JPA implementations can integrate with an application server’s managed transactions. If one takes advantage of this feature, one will control transactions by declarative demarcation or through the Java Transaction API (JTA) rather than through the EntityTransaction.

Entity Lifecycle Management

EntityManagers perform several actions that affect the lifecycle state of entity instances.

The persist() method, which belongs to the persistence unit, is used to add all necessary entities into the persistence context that can be managed by the EntityManager. For any data manipulation, such as Update, Delete, and even the execution of the persist() method, a Transaction Association must be started to monitor and execute this data manipulation. This is different with the data query, such as SELECT statement, in which no Transaction Association is needed.

Generally, to perform a data manipulation using the EntityManager and entities defined by the persistence unit, the following operational sequence should be executed:

1.An EntityManager instance that controls this data manipulation should be created.

2.A Transaction Association instance should be created using the getTransaction() method.

3.The created Transaction Association instance should be started by calling the begin() method.

4.Each entity instance involved in this data manipulation should be added into the persistence context by executing the persist() method one by one.

5.The data manipulation is performed by executing the commit() method.

6.The EntityManager instance should be closed after this data manipulation.

A piece of example codes used to insert two entities, magazine and publisher, into two entity classes that can be mapped to two tables, mag and pub, is shown in Figure 7.2.

AMagazine mag = new Magazine("1B78-YU9L", "JavaWorld");

BCompany pub = new Company("Weston House");

Cpub.setRevenue(1750000D);

mag.setPublisher(pub);

pub.addMagazine(mag);

DEntityManager em = emf.createEntityManager();

Eem.getTransaction().begin();

Fem.persist(mag);

em.persist(pub);

Gem.getTransaction().commit();

// or we could continue using the EntityManager...

Hem.close();

Figure 7.2. The operational sequence of perform a data manipulation using the EntityManager.

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

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

A.A new Magazine entity instance mag is created.

B.A new Company entity instance pub is created, too.

C.The entity instances are initialized using the setXXX() method to set all properties.

D.A new EntityManager instance is created that is used to manage this data manipulation.

E.A new Transaction Association instance is created and started using the getTransaction() and begin() method, respectively.

F.The persist() method is called two times to add these two entity instances into two entities.

G.The commit() method is called to execute this addition.

H.The EntityManager instance is removed if it is no longer to be used.

Now that we have a basic idea about the persistence unit, next, let’s develop our codes for the Insert button click event handler to perform a data insertion using the persist tool.

7.1.1.3 Develop the Codes for the Insert Button Event Handler

The main function of this handler is to insert a new faculty record with a set of new faculty information, including the faculty id, faculty name, office, title, phone, graduated college, and email. A photo is an optional to a new faculty record. In this application, to make it simple, we assume that a default image Default.jpg has been created for this new faculty. When inserting a new faculty record into the Faculty table, you have the option to insert a new faculty image by entering the location of that image into the Faculty Image Text Field, or no faculty image by leaving that Text Field empty.

Double click on the Insert button to open its event handler and enter the codes that shown in Figure 7.3 into the opened Insert button’s event handler.

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

ASelectQueryWizardPUEntityManager.clear();

Bfinal Faculty ft = new Faculty();

Cft.setFacultyId(FacultyIDField.getText());

ft.setFacultyName(FacultyNameField.getText());

ft.setTitle(TitleField.getText());

ft.setOffice(OfficeField.getText());

ft.setPhone(PhoneField.getText());

ft.setCollege(CollegeField.getText());

ft.setEmail(EmailField.getText());

Djavax.persistence.EntityTransaction trr = SelectQueryWizardPUEntityManager.getTransaction();

Eif (!trr.isActive()){

trr.begin();

}

FSelectQueryWizardPUEntityManager.persist(ft);

Gtrr.commit();

HComboName.addItem(FacultyNameField.getText());

}

Figure 7.3. The newly added codes to the Insert button click event handler.

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

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

A.First, we need to clean up the entity manager SelectQueryWizardPUEntityManager by calling the clear() method to make sure it is clean and ready to create new queries. The point to be noted is that this new EntityManager instance has been created before when we created and configured this FacultyFrame form window.

B.Since the JPQL did not provide a direct Insert command, therefore, we have to use the persist() method to do this insertion. To do that, a new Faculty entity instance ft is created.

C.The different setXXX() methods defined in the entity class Faculty.java are used to set a new faculty record with the inputs coming from seven Text Fields in the Faculty Information panel in the FacultyFrame form window. The getText() method is used to pick up seven pieces of information related to a new faculty member.

D.A new Transaction Association instance is created by calling the getTransaction() method. This step is necessary, since any data manipulation performed in the JPA must be under the control of a Transaction Association instance, and this is a significant difference to the data query operation such as the Select query.

E.Before we can start this Transaction instance, we must check whether a valid Transaction instance has been started and active. If not, we can start this Transaction to begin the data manipulation operation by executing the begin() method.

F.The persist() method is executed to add this new entity ft into the Faculty entity class.

G.The commit() method is called to start this transaction.

H.Finally, this new inserted faculty name is added into the Faculty Name combo box to enable users to check and validate this data insertion later.

Before we can build and run this project to test our codes, we prefer to first finish the coding development for the validation of this data insertion.

7.1.1.4 Develop the Codes for the Validation of the Data Insertion

In fact, we can use the codes we built in the Select button click event handler to perform this data insertion validation. No modification is needed for the codes developed in that event handler except the ShowFaculty() method.

The reason for us to modify the codes in the ShowFaculty() method is that a new faculty photo may be inserted when a new faculty record is inserted into the Faculty table. In order to coordinate this situation, we need to break this method into two separate methods, ShowFaculty() and DisplayImage().

The function of the DisplayImage() is used to only display a passed faculty image. The job of ShowFaculty() is to identify whether a new faculty image has been inserted with a data insertion, and perform the associated function based on this identification.

Open the ShowFaculty() method and perform the modifications shown in Figure 7.4. The modified part has been highlighted in bold.

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

A. First, we need to check whether a matched faculty image has been found or not. If a matched faculty image has been found, which means that the fImage != null, the matched faculty image is sent to the DisplayImage() method to be displayed.

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

private boolean ShowFaculty(){ int maxNumber = 7; String fImage = null;

String[] fname = {"Ying Bai", "Black Anderson", "Satish Bhalla", "Steve Johnson", "Jenney King", "Alice Brown", "Debby Angles", "Jeff Henry"};

String[] fimage = {"Bai.jpg", "Anderson.jpg", "Satish.jpg", "Johnson.jpg", "King.jpg", "Brown.jpg", "Angles.jpg", "Henry.jpg"};

for (int i=0; i<=maxNumber; i++){

if (fname[i].equals((String)ComboName.getSelectedItem())){ fImage = fimage[i];

break;

}

}

Aif (fImage != null){ DisplayImage(fImage);

Breturn true;

}

Celse if (FacultyImageField.getText() != null){ fImage = FacultyImageField.getText(); DisplayImage(fImage);

DFacultyImageField.setText("");

Ereturn true;

 

}

 

else

F

return false;

 

}

Figure 7.4. The modified codes for the ShowFaculty() method.

B.A true is returned to the calling method to indicate that the execution of the method

ShowFaculty() is successful.

C.Next, we need to check whether a new faculty image has been inserted with this data insertion. If a valid faculty image has been inserted, which means that the content of the FacultyImageField is a valid location where a faculty image file is stored, that location is assigned to the local variable fImage, and it is sent to the DisplayImage() method to be displayed in the Faculty Image box.

D.Immediately, this FacultyImageField is cleaned up by calling the setText() method, since this faculty image is only used for this data insertion, and we do not want this faculty photo to be used again in the future.

E.A true is returned to the calling method to indicate that this ShowFaculty() method has been executed successfully.

F.If both above conditions are not satisfied, which means that no matched faculty image can be found, a false is returned to the calling method to indicate that this method is failed, and no matched faculty photo can be found.

The detailed codes for the method DisplayImage() is shown in Figure 7.5.

The detailed explanation for this piece of codes has been given in Section 6.2.7.3.3.2 and Figure 6.56 in Chapter 6. Refer to that section to get a clear and detailed picture about this coding.

Now that we have finished developing the codes for data insertion and the data validation, let’s now build and run our project to test these functionalities.

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

private void DisplayImage(String facultyImage){ Image img;

int imgId = 1, timeout = 1000;

MediaTracker tracker = new MediaTracker(this);

MsgDialog msgDlg = new MsgDialog(new javax.swing.JFrame(), true);

img = this.getToolkit().getImage(facultyImage); Graphics g = ImageCanvas.getGraphics(); tracker.addImage(img, imgId);

try{

if(!tracker.waitForID(imgId,timeout)){ msgDlg.setMessage("Failed to load image"); msgDlg.setVisible(true);

}//end if }catch(InterruptedException e){

msgDlg.setMessage(e.toString()); msgDlg.setVisible(true);

}

g.drawImage(img, 0, 0, ImageCanvas.getWidth(), ImageCanvas.getHeight(), this);

}

Figure 7.5. The detailed codes for the method DisplayImage().

7.1.1.5 Build and Run the Project to Test the Data Insertion

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.

A default faculty image Default.jpg has been saved to our project folder, which is

C:\JavaDBProject\Chapter 7\SelectQueryWizard. You can find this image file from the folder Image that is located at the Wiley ftp site (refer to Figure 1.2 in Chapter 1). If you want to save your faculty image at any other folder you like, you need to enter the full name, which includes the path and the name of that image, into the Faculty Image Field as the project runs. You do not need to do this step if you do not want to insert any faculty image with the data insertion.

Now we are ready to build and run our project to test this data insertion and validation function.

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 seven Text Fields inside the Faculty Information panel as a new faculty record, as shown in Figure 7.6.

1.

Faculty ID: T56789

2.

Name:

Tom Jeff

3.

Title:

Associate Professor

4.

Office:

MTC-215

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

Figure 7.6. The newly inserted faculty record.

Figure 7.7. The newly added faculty name.

5.

Phone:

750-378-1155

6.

College:

Florida Atlantic University

7.

Email:

tjeff@college.com

Also, enter Default.jpg into the Faculty Image Field, since we want to insert a default faculty image with this data insertion. Then click on the Insert button to perform this data insertion. Immediately, you can find that a new faculty Tom Jeff has been added into the Faculty Name combo box when you click on the drop-down arrow of that combo box, as shown in Figure 7.7.

To confirm and validate this data insertion, we have two ways to go: one way is to open our sample database CSE_DEPT using either the Microsoft SQL Server Management

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

Figure 7.8. The opened Faculty table using the Services window in NetBeans IDE.

Figure 7.9. The retrieved inserted faculty information.

Studio Express or from the Services window in the NetBeans IDE, and another way is to click on the Select button on the FacultyFrame window to retrieve this inserted faculty record.

The opened Faculty table of our sample database CSE_DEPT is shown in Figure 7.8. It can be found that a new faculty record, which is highlighted, has been added into

the last row in our Faculty table.

Now select the new inserted faculty name Tom Jeff from the Faculty Name combo box and click on the Select button from the FacultyFrame window, seven pieces of newly inserted faculty information with the default faculty image is displayed on this form, as shown in Figure 7.9.

Click on the Back and Exit buttons to complete our project.

The running result of our project is successful, and a new faculty record has been inserted into our Faculty table successfully! It is highly recommended to remove this new inserted faculty record from our sample database since we want to keep our database

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

clean and neat. You can use Microsoft SQL Server Management Studio Express to do this deletion.

Next, let’s handle the data updating function to our Faculty table in our sample database.

7.1.2 Perform Data Updating to SQL Server Database Using JPA Wizards

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 first 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 modification 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 identifier 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 first 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 setParameter() 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.

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

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

Aint numUpdated = 0;

BString 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";

CSelectQueryWizardPUEntityManager.clear();

DfacultyQuery = SelectQueryWizardPUEntityManager.createQuery(query);

EfacultyQuery.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());

FfacultyQuery.setParameter("FacultyName", ComboName.getSelectedItem()); // reserve the current faculty name

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

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

Iif (!tr.isActive()){

tr.begin();

}

JnumUpdated = facultyQuery.executeUpdate();

Ktr.commit();

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

MComboName.addItem(FacultyNameField.getText());

NComboName.removeItem(cFacultyName);

}

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

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 confirm 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 transaction. 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.

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