Creating a Maven Swing Application Using Hibernate - NetBeans IDE Tutorial
In this tutorial, you use the NetBeans IDE to create a Java Swing application from a Maven archetype. The application uses the Hibernate framework as the persistence layer to retrieve POJOs (plain old Java objects) from a relational database. The tutorial demonstrates how wizards in the IDE can help you create the necessary Hibernate files and add Hibernate dependencies to the POM. After creating the Java objects and configuring the application to use Hibernate, you create a GUI interface for searching and displaying the data.
Support for Maven is fully integrated in NetBeans IDE and Maven 3 is bundled with the IDE. You can create applications from the bundled Maven archetypes or from archetypes in remote repositories in the New Project wizard. The Maven Repository Browser enables you to explore your local and remote Maven repositories, examine artifacts and add project dependencies to the project's POM.
To build this application using Ant, see Using Hibernate in a Java Swing Application.
To build a Maven Java EE application, see Creating an Enterprise Application Using Maven.
To follow this tutorial, you need the following software and resources.
Before starting this tutorial you may want to familiarize yourself with the following documentation.
You can download a zip archive of the finished project.
Creating the Database
This tutorial uses a MySQL database called sakila. The sample database is not included when you install the IDE so you need to first create the database to follow this tutorial.
The sakila database is a free sample MySQL database that is available from the MySQL site. To create the sakila database you can download and install the Sakila Sample Database plugin using the Plugins manager. After you install the plugin you can create the sakila database from the Services window. The sakila database is added to the list of databases in the Create MySQL database dialog box.
For more information on configuring the IDE to work with MySQL, see the Connecting to a MySQL Database tutorial.
When you click Connect, a database connection node for the Sakila database (jdbc:mysql://localhost:3306/sakila [username on Default]) is listed under the Databases node. When a connection is open you can view the data in the database by expanding the connection node.
Maven is bundled with the IDE and installed when you install the IDE, but if this is your first Maven project you will want to check the Maven configuration settings in the Options window.
Viewing the Maven Repositories
The artifacts that are used by Maven to build all your projects are stored in your local Maven repository. When an artifact is declared as a project dependency, the artifact is downloaded to your local repository from one of the registered remote repositories.
Several well-known indexed Maven repositories are registered and listed in the repository browser by default. The registered repositories contain most of the public artifacts necessary for you to build your project. In most cases, you do not need to register any additional repositories unless your project requires artifacts found only in a private repository.
You can explore your local and remote Maven repositories and perform an immediate check for updates in the Services window. Any artifact that is in your local or remote repositories can be added as a project dependency. You can expand the Local repository node in the Services window to see the artifacts that are present locally. The artifacts listed under the remote repository nodes can be added as project dependencies, but not all of them are present locally. They are only added to the Local repository when they are declared as project dependencies.
To browse and update the Maven repositories perform the following steps.
When your cursor is over an artifact, the IDE displays a tooltip with the artifact's coordinates. You can double-click an artifact's JAR file to view additional details about the artifact.
You can search for an artifact by right-clicking the Maven Repositories node in the Services window and choosing Find.
Notes for NetBeans IDE 7.1 and earlier versions of the IDE.
Creating the Maven Application
In this tutorial you create a simple Java Swing application project called DVDStoreAdmin. You will create the project from one of the bundled Maven archetypes and then modify the default project settings.
Choosing an Archetype
The New Project wizard enables you to create a Maven project from a Maven archetype. The IDE includes several archetypes for common NetBeans project types, but you can also locate and choose archetypes in remote repositories in the wizard.
When you click finish the IDE creates the Maven project and opens the project in the Projects window. The IDE automatically creates the class App.java in the com.mycompany.dvdstoreadmin package. You can delete App.java because the application does not need it.
Note. If this is the first time you are creating a Maven project, Maven will need to download some necessary plugins and artifacts to the local repository. This can take some time.
Modifying Project Properties
When you create a Maven project using the wizard, the default project properties are based on the archetype. In some cases, you may need to modify the default properties according to your system and the project's requirements. For example, for this project you want to confirm that the Source level is set to 1.5 or higher because the project uses annotations.
Adding Hibernate Files and Dependencies
To add support for Hibernate you need to make the Hibernate libraries available by declaring the necessary artifacts as dependencies in the POM. The IDE includes wizards to help you create the Hibernate files you may need in your project. You can use the wizards in the IDE to create a Hibernate configuration file and a utility helper class. If you create the Hibernate configuration file using a wizard the IDE automatically updates the POM to add the Hibernate dependencies to the project.
You can add dependencies to the project in the Projects window or by editing pom.xml directly. To add a dependency in the Projects window, right-click the Dependencies node in the Projects window and choose Add Dependency from the popup menu to open the Add Dependency dialog box. When you add a dependency, the IDE updates the POM and downloads any required artifacts to the local repository that are not already present locally.
To edit pom.xml directly, open the file by expanding the Project Files node in the Projects window and double-clicking pom.xml.
Creating the Hibernate Configuration File
The Hibernate configuration file (hibernate.cfg.xml) contains information about the database connection, resource mappings, and other connection properties. When you create a Hibernate configuration file using a wizard you specify the database connection by choosing from a list of database connection registered with the IDE. When generating the configuration file the IDE automatically adds the connection details and dialect information based on the selected database connection. The IDE also automatically modifies the POM to add the required Hibernate dependencies. After you create the configuration file you can edit the file using the multi-view editor, or edit the XML directly in the XML editor.
When you click Finish the IDE opens hibernate.cfg.xml in the editor. The configuration file contains information about a single database.
If you expand the Dependencies node in the Projects window you can see that the IDE added the required Hibernate artifacts. The IDE lists all direct and transitive dependencies required to compile the project under the Dependencies node. The artifacts that are direct dependencies (dependencies that are specified in the project's POM) are indicated by color JAR icons. An artifact is greyed out if it is a transitive dependency (an artifact that is the dependency of one or more direct dependencies).
You can view details of artifacts by right-clicking a JAR and choosing View Artifact Details. The Artifact Viewer contains tabs that provide details about the selected artifact. For example, the Basic tab provides details about the artifact's coordinates and available versions. The Graph tab provides a visual representation of the dependencies of the selected artifact.
You can also use the Graphs tab to discover and resolve version conflicts among dependencies.
Modifying the Hibernate Configuration File
In this exercise you will edit the default properties specified in hibernate.cfg.xml to enable debug logging for SQL statements. This exercise is optional.
When you run your project you will be able to see the SQL query printed in the IDE's Output window.
Creating the HibernateUtil.java Helper File
To use Hibernate you need to create a helper class that handles startup and that accesses Hibernate's SessionFactory to obtain a Session object. The class calls Hibernate's configure() method, loads the hibernate.cfg.xml configuration file and then builds the SessionFactory to obtain the Session object.
In this section you use the New File wizard to create the helper class HibernateUtil.java.
When you click Finish, HibernateUtil.java opens in the editor. You can close the file because you do not need to edit the file.
Generating Hibernate Mapping Files and Java Classes
In this tutorial you use a plain old Java object (POJO), Actor.java, to represent the data in the table ACTOR in the database. The class specifies the fields for the columns in the tables and uses simple setters and getters to retrieve and write the data. To map Actor.java to the ACTOR table you can use a Hibernate mapping file or use annotations in the class.
You can use the Reverse Engineering wizard and the Hibernate Mapping Files and POJOs from a Database wizard to create multiple POJOs and mapping files based on database tables that you select. Alternatively, you can use wizards in the IDE to help you create individual POJOs and mapping files from scratch.
Note. When you want to create files for multiple tables you will most likely want to use the wizards. In this tutorial you only need to create one POJO and one mapping file so it is fairly easy to create the files individually. You can see the steps for creating the POJOs and mapping files individually at the end of this tutorial.
Create Reverse Engineering File
To use the POJOs and Mapping Files from Database wizard, you need to first create the reveng.xml reverse engineering file in the src/main/resources directory where you created hibernate.cfg.xml.
The wizard generates a hibernate.reveng.xml reverse engineering file. You can close the reverse engineering file because you will not need to edit the file.
Note. This project requires a MySQL connector jar library (mysql-connector-jar-5.1.13.jar, for example). If a suitable JAR is not listed as a project dependency under the Dependencies node, you can add the dependency by right-clicking the Dependencies node and choosing Add Dependency.
Creating Hibernate Mapping Files and POJOs From a Database
The Hibernate Mapping Files and POJOs from a Database wizard generates files based on tables in a database. When you use the wizard, the IDE generates POJOs and mapping files for you based on the database tables specified in hibernate.reveng.xml and then adds the mapping entries to hibernate.cfg.xml. When you use the wizard you can choose the files that you want the IDE to generate (only the POJOs, for example) and select code generation options (generate code that uses EJB 3 annotations, for example).
When you click Finish, the IDE generates the POJO Actor.java with all the required fields in the src/main/java/sakila/entity directory. The IDE also generates a Hibernate mapping file in the src/main/resources/sakila/entity directory and adds the mapping entry to hibernate.cfg.xml.
Now that you have the POJO and necessary Hibernate-related files you can create a simple Java GUI front end for the application. You will also create and then add an HQL query that queries the database to retrieve the data. In this process we also use the HQL editor to build and test the query.
Creating the Application GUI
In this exercise you will create a simple JFrame Form with some fields for entering and displaying data. You will also add a button that will trigger a database query to retrieve the data.
If you are not familiar with using the GUI builder to create forms, you might want to review the Introduction to GUI Building tutorial.
Creating the JFrame Form
When you click Finish, the IDE creates the class and opens the JFrame Form in the Design view of the editor.
Adding Elements to the Form
You now need to add the UI elements to the form. When the form is open in Design view in the editor, the Palette appears in the right side of the IDE. To add an element to the form, drag the element from the Palette into the form area. After you add an element to the form you need to modify the default value of the Variable Name property for that element.
In Design view your form should look similar to the following image.
Now that you have a form you need to create the code to assign events to the form elements. In the next exercise you will construct queries based on Hibernate Query Language to retrieve data. After you construct the queries you will add methods to the form to invoke the appropriate query when the Query button is pressed.
Creating the Query in the HQL Query Editor
In the IDE you can construct and test queries based on the Hibernate Query Language (HQL) using the HQL Query Editor. As you type the query the editor shows the equivalent (translated) SQL query. When you click the 'Run HQL Query' button in the toolbar, the IDE executes the query and shows the results at the bottom of editor.
In this exercise you use the HQL Editor to construct simple HQL queries that retrieve a list of actors' details based on matching the first name or last name. Before you add the query to the class you will use the HQL Query Editor to test that the connection is working correctly and that the query produces the desired results. Before you can run the query you first need to compile the application.
Testing the queries shows that the queries return the desired results. The next step is to implement the queries in the application so that the appropriate query is invoked by clicking the Query button in the form.
Adding the Query to the Form
You now need to modify DVDStoreAdmin.java to add the query strings and create the methods to construct and invoke a query that incorporates the input variables. You also need to modify the button event handler to invoke the correct query and add a method to display the query results in the table.
After you save the form you can run the project.
Running a Maven Project
Now that the coding is finished, you can build the project and launch the application. When you build a Maven project in the IDE, Maven reads the project's POM to identify the project dependencies. All the artifacts specified as dependencies must be in your local Maven repository in order to build the project. If a required artifact is not in the local repository, Maven will checkout the artifact from a remote repository before attempting to build and run the project. After building the project, Maven will install the resulting binary as an artifact in your local repository.
To compile and launch this application, perform the following tasks.
When you invoke the Run action on a Maven project in the IDE, the IDE runs the Maven goals associated with the Run action. The IDE has default goals bound to IDE actions according to the project packaging. You can view the goals bound to the Run action in the Actions pane of the project's Properties window
You can customize the binding of goals to actions in the Actions pane of the project's Properties window.
The GUI form opens when you launch the application. Type in a search string in the First Name or Last Name text field and click Query to search for an actor and see the details.
If you look in the Output window of the IDE you can see the SQL query that retrieved the displayed results.
Downloading the Solution Project
You can download the solution to this tutorial as a project in the following ways.
Creating POJOs and Mapping Files Individually
Because a POJO is a simple Java class you can use the New Java Class wizard to create the class and then edit the class in the source editor to add the necessary fields and getters and setters. After you create the POJO you then use a wizard to create a Hibernate mapping file to map the class to the table and add mapping information to hibernate.cfg.xml. When you create a mapping file from scratch you need to map the fields to the columns in the XML editor.
Note. This exercise is optional and describes how to create the POJO and mapping file that you created with the Hibernate Mapping Files and POJOs from Database wizard.
After you create the POJO for the table you will want to create an Hibernate Mapping File for Actor.java.
Creating individual POJOs and Hibernate mapping files might be a convenient way to further customize your application.
For additional information on creating Swing GUI applications, see the following tutorials.