JAVA PERSISTENCE API WIZARDS
7.1 PERFORM DATA MANIPULATIONS TO SQL SERVER DATABASE USING JPA WIZARDS
7.1.1 Perform Data Insertion to SQL Server Database Using
We want to use and modify a fi nished project SelectQueryWizard we built in the last chapter to develop the data insertion function using the JPA wizards. Perform the follow- ing 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 SelectQueryWizard 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 SQL Server 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 SQL Server 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.1.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).
Perform the following operations to open our pasted project SelectQueryWizard : 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 SelectQueryWizard , 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.
3. The point to be noted is that you now have two SelectQueryWizard projects in the NetBeans IDE, but they are different projects with different functions. The fi rst
SelectQueryWizard was built in Chapter 6 without data manipulation function, but this second project will be built in Chapter 7 with the data manipulation function.
4. Expand this project fi les to open the FacultyFrame.java fi le by double clicking on this fi le that is located under the Source Packages\LogInFramePackage node.
5. 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 fi elds 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.1 .
Table 7.1. Objects and controls added into the faculty frame window
Type Variable Name Text editable Title
Label Label1 Faculty ID Text Field FacultyIDField No check Label Label2 Name Text Field FacultyNameField checked Label Label3 Faculty Image Text Field FacultyImageField checked
c07.indd 465
c07.indd 465 7/20/2011 11:12:02 AM7/20/2011 11:12:02 AM
www.traintelco.com
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 fi nished modifi ed 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, fi rst, 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 life- cycle are managed. The EntityManager interface defi nes the methods that are used to interact with the persistence context. The EntityManager API is used to create and remove persistent entity instances, to fi nd entities by their primary key, and to query over entities.
The set of entities that can be managed by a given EntityManager instance is defi ned by a persistence unit. A persistence unit defi nes 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 inter- act with the JPA runtime. The methods of the EntityManager can be divided into the following functional categories:
Figure 7.1. The modifi ed FacultyFrame form window.
• 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 defi ned 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 .
Figure 7.2. The operational sequence of perform a data manipulation using the EntityManager.
Magazine mag = new Magazine("1B78-YU9L", "JavaWorld");
Company pub = new Company("Weston House");
pub.setRevenue(1750000D);
mag.setPublisher(pub);
pub.addMagazine(mag);
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
em.persist(mag);
em.persist(pub);
em.getTransaction().commit();
// or we could continue using the EntityManager...
em.close();
A B C
D E F G H
c07.indd 467
c07.indd 467 7/20/2011 11:12:02 AM7/20/2011 11:12:02 AM
www.traintelco.com
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 getTransac- tion() 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, offi ce, 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.
Figure 7.3. The newly added codes to the Insert button click event handler.
private void cmdInsertActionPerformed(java.awt.event.ActionEvent evt) { // TODO add your handling code here:
SelectQueryWizardPUEntityManager.clear();
final Faculty ft = new Faculty();
ft.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());
javax.persistence.EntityTransaction trr = SelectQueryWizardPUEntityManager.getTransaction();
if (!trr.isActive()){
trr.begin();
}
SelectQueryWizardPUEntityManager.persist(ft);
trr.commit();
ComboName.addItem(FacultyNameField.getText());
} A
B C
D E
F G H
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 confi gured 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 defi ned 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 signifi cant 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 fi rst fi nish 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 modifi cation 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 identifi cation.
Open the ShowFaculty() method and perform the modifi cations shown in Figure 7.4 . The modifi ed part has been highlighted in bold.
Let ’ s have a closer look at this piece of modifi ed 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.
c07.indd 469
c07.indd 469 7/20/2011 11:12:03 AM7/20/2011 11:12:03 AM
www.traintelco.com
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 fi le is stored, that loca- tion 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 satisfi ed, 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 fi nished developing the codes for data insertion and the data vali- dation, let ’ s now build and run our project to test these functionalities.
Figure 7.4. The modifi ed codes for the ShowFaculty() method.
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;
} }
if (fImage != null){
DisplayImage(fImage);
return true;
}
else if (FacultyImageField.getText() != null){
fImage = FacultyImageField.getText();
DisplayImage(fImage);
FacultyImageField.setText("");
return true;
} else
return false;
} A B C
D E
F
Figure 7.5. The detailed codes for the method DisplayImage().
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);
}
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 fi nd this image fi le 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 valida- tion 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. Offi ce: MTC - 215
c07.indd 471
c07.indd 471 7/20/2011 11:12:03 AM7/20/2011 11:12:03 AM
www.traintelco.com
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 fi nd 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 confi rm 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
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
Figure 7.8. The opened Faculty table using the Services window in NetBeans IDE.
Figure 7.9. The retrieved inserted faculty information.
c07.indd 473
c07.indd 473 7/20/2011 11:12:03 AM7/20/2011 11:12:03 AM
www.traintelco.com