At first, part of JavaFX tutorial series, we created a sample JavaFX project, designed the draft version of the UI and set up an Oracle XE database. In this post, we will create controller, model, DAO, and Util classes to do DB operations. Before starting to code, I want to give more information about our example project.  The latest version of the UI is shown in the figure below.

database operations

You can design UI using SceneBuilder. After drag and drop any element to the anchor pane, you need to set their fx:id properties. These properties must be unique and you can use elements in your code with their unique fx:id properties. Also, you can copy paste any element on anchor pane then change its name and fx:id value. I demonstrated how to design a GUI in the figure below.

GUI

I listed details of the example below:

  • Search an employee using employee’s id and show the result on table view and text area. (SELECT)
  • Search all employees and show them on the table view. (SELECT * FROM)
  • Update the e-mail address of an employee by using employee’s id. (UPDATE)
  • Delete an employee by using employee’s id. (DELETE)
  • Insert a new employee to the “employee table”. (INSERT)
  • Show results of all operations on the Text Area (Print on Result Console)

We will use Oracle XE database and its default HR schema. In order to connect Oracle DB, we will use JDBC driver. JDBC driver is a software component enabling a Java application to interact with a database. To add JDBC driver in our project:

1) Go to your project, right-click, and then click Open Module Settings.

javafx

2) Click Libraries then click “+” sign, click “From Maven

maven

3) Write “odjbc” on search bar and enter. Then, select the “oracle:ojdbc6:11.2.0.3” and select sources and JavaDocs click OK.

2-5

2-6

2-7

4) Now, we can see ojdbc6:11.2.0.3 library in lib folder on IntelliJ.

2-8

Finally, we are ready to start coding. As shown the picture below, I created 4 packages: controller, model, view and util.

packages

I used DAO Design Pattern to perform Employee operations. I want to explain DAO Pattern briefly, for more information, I suggest that you check Jakop Jenkov’s DAO tutorial. In DAO pattern, domain (business) logic does not directly communicate with the DB. It communicates with DAO layer and DAO layer handles DB operations and sends the results to the business layer.

dao pattern

The philosophy under DAO pattern is that if you need to change the underlying persistence mechanism, you can do it in DAO layer, not all the places in the business layer. It is also very important that no details of underlying DB related mechanism leak out of DAO layer to business layer.

DBUtil Class

I want to start to explain the code with DBUtil class. In our example, DBUtil class is responsible for DB connection, DB disconnection, database query and update operations. DAO Class (EmployeeDAO) uses DBUtil class’s methods to do higher-level DB operations.

In DBUtil Class:

– dbConnect() method connects to DB.

– dbDisconnect() method closes DB connection.

dbExecuteQuery(String queryStmt) method executes given SQL statement and returns cachedRowSet set. In order to eliminate “java.sql.SQLRecoverableException: Closed Connection: next” error we return cachedRowSet instead of ResultSet. Thus, we can use cachedRowSet in other classes and manipulate that data.

dbExecuteUpdate(String sqlStmt) method executes given Update, Insert, Delete SQL operations.

I tried to write explanatory comments in the code below. If you have questions please don’t hesitate to write a comment. I will try to answer your questions.

DBUtil Class Code:

Employee Class (Model)

We need a model class to hold information about the employee. Add a new class to the model package and called it Employee.

2-10

This class holds all fields of the Employee such as name, last name, email, etc. It contains set and get methods and properties for all fields of a model class. A Property notifies us when any variable such as name, last name, etc. is changed. This helps us keep the view in sync with the data.

You can see the all fields of the employee from database as shown below.

employee

Employee Class Code:

Employee DAO Class (Data Access Object)

Employee DAO class handles employee related database operations such as searching, deleting, updating employee with declared SQL statements.

JavaFX view classes need to be informed about any changes made to the list of employees. It is important for the view to be synchronized with the data. For this purpose, we use ObservableList collection and hold the employee in this list.

  • searchEmployee and searchEmployees methods use DBUtil class’s dbExecuteQuery() method.
  • The other methods (update/delete/insert), use DBUtil class’s dbExecuteUpdate() method.

I tried to add descriptive inline comments in the code shown below.

EmployeeDAO Class Code:

RootLayout FXML

RootLayout contains a border pane and menu items. We need to bind it with RootLayoutController class.

2-12

We have three menus: File, Operations, and Help.

2-13

File Menu has Close option to exit the program. Operations menu has “New Menu Item” option.  Help Menu has “About” option to show information about program.

RootLayout View Code:

EmployeeView FXML

EmployeeView fxml file comprises of text fields, buttons, table view and text area for employee related operations. We need to bind it with EmployeeController class.

2-14

As you see the picture below, we need to declare fx:id values, these values are unique for each element and we can bind methods with these elements by OnAction tag. Methods must start with “#” sign.

2-15

Employee View Code:

RootLayoutController Class

In RootLayoutController class, we handle exit and help methods. Exit method closes program and help method gives information about program by using Alert class.

RootLayoutController Code:

EmployeeController Class

In EmployeeController class, fields and methods have special @FXML annotation. We need this annotation because fxml file needs to access private fields and private methods. After these settings, application will automatically fill the variables when the fxml file is loaded.

EmployeeController Class handles below operations:

– searchEmployee() – Searches an employee with given employee id. Then, populate employee’s information on table view and print the result on text area.

– searchEmployees() – Gets all employees information and populates them on table view.

initialize() – Handles initialization. When the fxml file is loaded, it will be called automatically.

– populateEmployee(Employee) – Populates employee on table view.

– setEmpInfoToTextArea(Employee) – Prints employee information on text area.

– populateEmployees(ObservableList<Employee>) – Populates employees.

– updateEmployeeEmail() – Updates employee email by using employee id

– insertEmployee() – Insert a new employee into employee table.

– deleteEmployee() – Deletes an employee with employee’s id.

Extra Explanations:

– Private fields and methods where the fxml file needs to access must be annotated with @FXML annotation.

– After the fxml file has been loaded, the initialize() method will be called automatically.

– The setCellValueFactory(…) that we set on the table columns are used to determine which field inside the Employee objects should be used for the particular column. The arrow -> indicates that we are using a Java 8 feature called Lambdas. (Another option would be to use a PropertyValueFactory).

– If you use a property which is different than StringProperty, such as IntegerProperty, DoubleProperty, etc. the setCellValueFactory(…) must have an additional asObject() method:

Note: Always use the javafx imports, NOT awt or swing!

EmployeeController Class Code:

Main Class

At the end of the first JavaFX article, I described details of the main method. In here, I want to explain it briefly. It starts the primary stage, sets its title, initializes the root layout and then displays the “employee view”.

Main Class Code:

We finished coding. It is time to run the code.

2-16

The result of the program is shown below.

2-17

Github: https://github.com/swtestacademy/javafxexample

Bonus Information (Multi-threaded JavaFX Database Operations)

Sometimes big queries takes too much time and GUI is frozen until the query finishes. In order to solve this problem, we need to write our code in a multi threaded way. In this example, you can search all employees with multi-threaded way as follows:

First, you need to add an Executor variable and add below code snippet in EmployeeController Class’s initialize method:

Then, you can use JAVA Task class to handle data table populate operations with below code.

You can use fillEmployeeTable method instead of populateEmployees method. In this example, our data is not too big so I don’t need to use multi-threaded function for data populate operation but if you work with data intensive project, you may need to use multi-threaded functions to eliminate Frozen GUI  problems.

The End 🙂

Java FX Tutorial Series

JavaFX – Part 1: Getting Started with JavaFX

JavaFX – Part 2: JavaFX Database Operations (This Post)