< Insert, Update, Delete & JPA (MySQL) | Main | Insert, Update, Delete & JPA ver 2 (MySQL) >

 


 

 

Java Web GUI Application:

Using Java Persistence API (JPA) in Visual Web JSF Application (MySQL) Version 2 Part 1

 

 

 

This is a version 2 part 1 tutorial on JSP, JPA, JSF and MySQL.

 

Contents:

  1. Creating a Database Using MySQL Command Line Client

  2. Making a Connection to the Database Using NetBeans

  3. Creating a Table Using an SQL Script

  4. Inserting a Sample Data Using SQL Script

  5. Linking a Visual Web Project to a Java Standard Edition Project

  6. Creating the Projects

  7. Linking the Projects Together

  8. Binding to a Database Table

  9. Connecting to the Database

  10. Creating a Java Persistence Entity Class Representing the Users Database Table

  11. Creating a Persistence Unit

  12. Setting Key Attributes With Java Persistence Annotations

  13. Creating the Classes

  14. Creating the Entity Controller Class

  15. Binding the Entity Bean to the Table Component

  16. Creating a Property in the Session Bean

  17. Creating the Initialization Method

  18. Binding the Property to the Table Component

  19. Doing Some Customization

  20. Creating a Database Using MySQL Command Line Client

 

Firstly, create a database named student. Execute the following SQL statement.

 

CREATE DATABASE student;

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

Then verify using show database; statement and exit MySQL Command Line Client. Launch NetBeans.

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

Making a Connection to the Database Using NetBeans

 

We will create a Users table that consists of five columns, as follows. However we will not use the photo columns in this tutorial.

 

 

In NetBeans, connect to the student database by following the steps shown in the following Figures.

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

Fill in the MySQL connection string, user name and its password and click OK. In this case we are using root user.

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

By expanding the connection node, we can re-confirm that the connection was established.

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

Creating a Table Using an SQL Script

 

Next, launch the query editor.

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

Execute the following SQL script.

 

CREATE TABLE Users(

studentId INTEGER(10) NOT NULL AUTO_INCREMENT,

name VARCHAR(50),

email VARCHAR(30),

contactNo VARCHAR(30),

photo BLOB,

PRIMARY KEY (studentId)

)type=innodb;

 

We include the BLOB data type just for a demonstration. This BLOB data type can be used to store binary such as images, files etc. in the table. (We do not implement this feature in the web page for this tutorial; just leave it in the table). Optionally, if you want to start the index from 8700 for example, execute the following script and we implement this in this tutorial so no need for us to worry about the primary key and validation for the studentId input by user.

 

ALTER TABLE Users AUTO_INCREMENT = 8700;

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

Inserting a Sample Data Using SQL Script

 

Insert some sample data by executing the following script. You need to have some images that stored in the C:\your_butterfly_folder for this script to be executed properly. Change the path and the image files name accordingly. These images will be used in another tutorial if possible.

INSERT INTO Users(name, email,contactNo,photo)

 VALUES ('Stephanie Lame', 'stephanie@aol.com', '808-2341567', LOAD_FILE('C:\\butterfly\\butterfly1.jpg'));

INSERT INTO Users(name, email,contactNo,photo)

 VALUES ('Meg Ryan', 'ryan@gmail.com', '808-7681569', LOAD_FILE('C:\\butterfly\\butterfly2.jpg'));

INSERT INTO Users(name, email,contactNo,photo)

 VALUES ('Jodie Foster', 'foster@yahoo.com', '808-2348710', LOAD_FILE('C:\\butterfly\\butterfly3.jpg'));

INSERT INTO Users(name, email,contactNo,photo)

 VALUES ('Amar Maarof', 'amar@gmail.com', '604-7364518', LOAD_FILE('C:\\butterfly\\butterfly4.jpg'));

INSERT INTO Users(name, email,contactNo,photo)

 VALUES ('Alif Nijar', 'nijar@aol.com', '705-4452345', LOAD_FILE('C:\\butterfly\\butterfly5.jpg'));

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

Verify our data insertion by following the steps shown in the following Figure.

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

The following shows the example of an index that start from 8700.

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

Linking a Visual Web Project to a Java Standard Edition Project

 

To use the Java Persistence API from a Visual Web application, you actually create two projects. One project is your Visual Web project. The other is a Java Standard Edition (SE) application project that includes several classes whose code the web application will call. From within this Java SE application project, you generate a persistence unit to get a handle to the Java Persistence API. Your web application then uses the classes created in the Java SE application project to establish the database binding, and later to do the database update, delete, and add operations.

 

Creating the Projects

 

1.      Create the Java SE application project. Begin by creating the Java SE application project, which is a general Java project. Click the New Project icon in the toolbar (Ctrl+Shift+N), then select Java in the Categories column and Java Application in the Projects column. Then click Next.

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

2.      In the New Java Application screen, set the project name to TheModelApp. You also need to set the package to com.users.model. You can do this by changing the default Create Main Class entry from themodelapp.Main to com.users.model.Main. Click Finish.

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

3.      Create the Visual Web project. From the New Project dialog, select Web as the category and Web Application as the project, then click Next.

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

4.      In the New Web Application dialog, set the project name to TheWebApp. The project location should default to the same location as the TheModelApp project. Click Next to go to the screen where you select the framework.

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

5.      Select Visual Web JavaServer Faces for the framework. When you make this selection, the screen displays configuration settings. Change the Default Java Package setting from thewebapp to com.users.web. Click Finish.

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

Both TheModelApp and TheWebApp nodes can be seen in the project window.

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

Linking the Projects Together

 

Now you want to link the two projects together. Specifically, you want the MyTestModelApp project to be a dependency of the MyTestWebApp project. To make MyTestModelApp a dependent project of MyTestWebApp, you need to add the MyTestModelApp.jar file to the MyTestWebApp project. Here's how to do this:

 

1.      In the Projects window, right Click the TheWebApp project node and select Properties from its context menu.

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

2.      In the Project Properties dialog, click the Libraries node in the Categories section on the left. Then, click Add Project.

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

3.      In the Add Project window, browse to the location with the TheModelApp project and select it. Then click Add Project JAR Files. This step adds the TheModelApp jar file to the compile-time libraries for the TheWebApp project, and TheModelApp appears in the Project Properties screen. Click OK in the Project Properties screen to complete the process.

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

Binding to a Database Table

 

You use the Java Persistence API to convey information back and forth from a database table to the table visual component that's used in the Visual Web JSF application. After you do this binding, you use the API to retrieve rows from the database table, but you display the data using the Visual Web Table component's built-in display features.

 

Connecting to the Database

 

To begin, you connect to the database with the Users table from within the MyTestWebApp project. If you are not yet connected to it, open the Services window, expand the Databases node, open the context menu for the jdbc:mysql://localhost:3306/student [root on Default Schema] node and choose Connect. If you are using a different DBMS, then, if needed, set up a driver for that database and create a new connection, providing the necessary connection parameters. We have completed this task.

From the Services window, verify that the connection to the database is established. Open the Databases > student database Tables node and verify that the users table is correct.

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

Creating a Java Persistence Entity Class Representing the Users Database Table

 

Create an entity class representing the Users table. As noted previously, the entity class is the Java Persistence representation of the database table definition. JPA uses Java language annotation feature to mark Plain Old Java Objects (POJOs) as JPA entities with information on object-relation mapping. Create the entity class from within the TheModelApp project using the Entity Classes from Database function.

 

1.      In the Projects (or Files) window, right click the TheModelApp project. From the context menu, select New > Entity Classes from Database.

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

 

2.      The New Entity Classes from Database Database Tables dialog displays. If the Database Connection field is blank, then select the student database from the pull-down list. The Available Tables column displays all the tables in the sample database, including the users table. Select the users table and click Add to move users to the Selected Tables column. Click Next after moving the users table.

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

3.      The Entity Classes dialog displays. The IDE displays the database table name users, and suggests a class name of Users. (Double click this class name to change it, if you want.) The dialog also indicates that the package is com.users.model. Click Create Persistence Unit.

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

Creating a Persistence Unit

 

1.      In the Create Persistence Unit dialog, set the Persistence Unit Name to usersPU. Leave the other fields with the default values. Click Create, then click Finish in the Entity Classes screen to complete the operation and create the samplePU persistence unit.

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

2.      It is a good idea to verify that the persistence unit is created correctly. To do so, expand the TheModelApp Source Packages > META-INF node and double click the persistence.xml file. The Design window displays information about the persistence unit, while the Navigator window shows the XML properties.

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

3.      Click the XML tab to see the complete XML listing. The properties in the file should correctly reflect the database name, its url, driver, and password, along with the package and class name (com.student.model.Users). The transaction type is RESOURCE_LOCAL and the provider is oracle.toplink.essentials.PersistenceProvider. Important: Be sure that the password field is filled in correctly.

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

Setting Key Attributes With Java Persistence Annotations

 

If you are working with the Derby database, you need to make some modifications to the generated Users.java code to handle auto generation of the primary key value. However, other database systems may handle primary key value generation differently, and any modifications you make to the generated Users.java class must match the underlying database's primary key generation policies. In this case we are using MySQL so we can skip this step. If we fail later, we will come back to this step.

 

Creating the Classes

 

Creating the Entity Controller Class

 

You continue to work in the TheModelApp project, creating a new class called UserController in the com.users.model package. (We provide the code for this class below, and you can paste it into your class.) Expand the TheModelApp > Source Packages > com.users.model.

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

Notice that there are already two classes in the package: Main.java and Users.java. Right click the com.users.model node and select New > Java Class.

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

In the New Java Class dialog, set the class name to UserController (leave the location as Source Packages and the package name as com.student.model). Click Finish.

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

You should see the skeleton source code for this new class in the Edit window.

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

Add the following code to the class:

private EntityManagerFactory emf;

 

    private EntityManager getEntityManager() {

        if (emf == null) {

            emf = Persistence.createEntityManagerFactory("usersPU");

        }

        return emf.createEntityManager();

    }

 

    public Users[] getUsers() {

        EntityManager em = getEntityManager();

        try {

            javax.persistence.Query q = em.createQuery("select c from Users as c");

            return (Users[]) q.getResultList().toArray(new Users[0]);

        } finally {

            em.close();

        }

    }

Use the Fix Imports function to import the required classes. (Right click in the source editor window and select Fix Imports from the pop-up menu.)

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

Doing so adds the following three import statements to the class:

 

import javax.persistence.EntityManager;

import javax.persistence.EntityManagerFactory;

import javax.persistence.Persistence;

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

You can use the Format function, available from the same pop-up menu, to format the code alignment.

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

Notice that the UserController class includes the method getUsers, which invokes the createQuery method on the javax.persistence.EntityManager interface to create a query that returns the rows of data from the Users table. The results of the query are returned as an array.

 

Binding the Entity Bean to the Table Component

 

You are ready to bind the entity component for accessing the Users database table to a Table component in the MyTestWebApp project. (Recall that you created the entity bean in the TestModelApp.) You do this binding from within the MyTestWebApp project. Here are the binding steps:

 

 

Let's examine these steps in more detail.

 

Creating a Property in the Session Bean

 

In the NetBeans IDE, you can find managed beans in several locations: in the Navigator window, in the source packages node in the Projects window, and in the src > java > project-name node in the Files window.

 

1.      First, create a property in SessionBean1 that returns an array of users objects. In the Navigator window, double click SessionBean1 to open it in the Java Source Editor. Or, double click SessionBean1 from within the Projects window MyTestWebApp > Source Packages > com.student.web node. If you do not see the Navigator window, try displaying a page from TestWebApp, such as Page1, in the Design window. The Navigator window should display beneath the Projects window. If you still do not see the Navigator window, click the Design tab in the Design window.

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

2.      Add a property called users to SessionBean1. Type in the following line of code:

 

private Users[] users;

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

3.      Fix imports. Most likely, the line you just entered will be marked as an error. If so, use the source editor's context menu Fix Imports function to fix this error. (Be sure to correct this error before continuing to the next step.) To fix the error, the IDE adds the following import statement: import com.users.model.Users;

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

 

4.      Generate get and set methods for the users property. Right click the line of code you typed in and select the action Insert Code. Choose Getter and Setter from the popup menu. Then, select users: Users[ ].

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

The Insert Code action adds public get and set methods. When finished, SessionBean1 should include the following code.

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

Creating the Initialization Method

 

1.      Add a method called updateUsers to SessionBean1. This method will be used to initialize the users property. Here's the code for the method:

 

public void updateUsers(){

     UserController usersController = new UserController();

     users = usersController.getUsers();

      }

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

2.      Use the Fix Imports function to fix the import needed for updateUsers. If there are errors in the code, do a Save All files to clear them.

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

3.      Add a call to the updateUsers method in the SessionBean1 init method: updateUsers();. The SessionBean1 init method should look as follows (comment lines not shown):

 

public void init(){

     super.init();

     try {

          _init();

     } catch (Exception e) {

          log("SessionBean1 Initialization Failure", e);

          throw e instanceof FacesException ? (FacesException) e: new FacesException(e);

     }

     updateUsers();

 }

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

4.      Save all the files.

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

5.      Build both the TheModelApp and TheWebApp projects.

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

Binding the Property to the Table Component

 

Now you are ready to bind the users property you just added to a Table component.

 

1.      From TheWebApp > Web Pages, double click Page1.jsp to open the page in the Design window.

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

2.      Drag a Table component from the Palette and drop it on the page in the Design window. It should as follows:

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

3.      Right click the Table component on the page and click Bind to Data from its context menu.

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

4.      In the Get Data From drop down list, select users (from SessionBean1) as the binding array. (Note that if you do not see the users property displayed in the drop down list, right click in the Design window and click the Refresh option in the context menu. Or simply click the Refresh button in the toolbar. If you still do not see the users property displayed in the drop down list, then close and reopen the TheWebApp project.) Click OK.

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

5.      The Table component display in the Design window should change to the following. If needed, adjust the columns to be displayed.

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

6.      Deploy and run the TheWebApp project.

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

7.      Make sure there is no error that can be seen in the Output windows for the project and the GlassFish web server as well.

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

8.      Make sure there is no error that can be seen in the Glassfish Output windows.

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

9.      The Table component displays, and, if you inserted sample data for the database table, that data should be displayed as shown here:

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

Doing Some Customization

 

1.      Next, let do some customization to our table. Right click the table and select the Table Layout from the context menu.

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

2.      Unselect the photo. We will use this for another tutorial later.

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

3.      Change the Header Text for all the column as shown in the following table.

 

From

To

contactNo

Contact No

email

Email

name

Name

studentId

Student Id

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

4.      Click the Options tab and change the table’s title to Users Record.

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

5.      Resize the table if needed. Re-run the project to see the effect.

 

Java web application using NetBeans: JSF, JPA and JSP technologies with MySQL database screenshots

 

We will continue to add more features for this application in the next tutorial, Part 2.

 

 

 

 

 

 

 

 


 

< Insert, Update, Delete & JPA (MySQL) | Main | Insert, Update, Delete & JPA ver 2 (MySQL) >