Using Hibernate in A Java Swing Application
Using Hibernate in A Java Swing Application
Using Hibernate in A Java Swing Application
In this tutorial, you use the NetBeans IDE to create and deploy a Java Swing application that displays data
from a database. The application uses the Hibernate framework as the persistence layer to retrieve POJOs
Hibernate is framework that provides tools for object relational mapping (ORM). The tutorial demonstrates
the support for the Hibernate framework included in the IDE and how to use wizards to create the necessary
Hibernate files. After creating the Java objects and configuring the application to use Hibernate, you create a
The application that you build in this tutorial is a companion administration application for the DVD Store
web application. This tutorial covers how to create an application that allows you to query an actor's profile
based on the match with first name or last name. If you wish you can extend the application to query film
details and to add/update/delete items. This tutorial uses MySQL and the Sakila database, but you can use
any supported database server with Hibernate applications. The Sakila database is a sample database that
you can download from the MySQL site. Information for setting up the Sakila DB is provided in the following
sections.
Before starting this tutorial you may want to familiarize yourself with the following documentation.
To build this application using Maven, see Creating a Maven Swing Application Using Hibernate.
Contents
To follow this tutorial, you need the following software and resources.
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.
1. Open the Plugins manager and install the Sakila Sample Database plugin.
2. After installing the plugin, start the MySQL database server by expanding the Databases
node in the Services window, right-clicking the MySQL Server node and choosing Start.
4. Select the Sakila database from the New Database Name drop down list in the Create
When you click OK a Sakila node appears under the MySQL Server node.
When you click Connect a database connection node for the Sakila database
node. When a connection is open you can view the data in the database by expanding the connection node.
1. Choose File > New Project (Ctrl-Shift-N). Select Java Application from the Java category
2. Type DVDStoreAdmin for the project name and set the project location.
For this tutorial there is little reason to copy project libraries to a dedicated folder because you
When you click Finish, the IDE creates the Java application project. The project does not have a main class.
You will create a form and then set the form as the main class.
Adding Hibernate Support to the Project
To add support for Hibernate to a J2SE project you need to add the Hibernate library to the project. The
Hibernate library is included with the IDE and can be added to any project by right-clicking the 'Libraries'
node in the Projects window, selecting 'Add Library' and then selecting the Hibernate library in the Add
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 adds the Hibernate libraries to the project.
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 adds
the Hibernate library to the project classpath. 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.
1. Right-click the Source Packages node in the Projects window and choose New > Other to
2. Select Hibernate Configuration Wizard from the Hibernate category. Click Next.
3. Keep the default settings in the Name and Location pane (you want to create the file in the
4. Select the sakila connection in the Database Connection drop down list. Click Finish.
When you click Finish the IDE opens hibernate.cfg.xml in the source editor. The IDE creates the
configuration file at the root of the context classpath of the application (in the Files window, WEB-
INF/classes). In the Projects window the file is located in the <default package> source package. The
configuration file contains information about a single database. If you plan to connect to multiple databases,
you can create multiple configuration files in the project, one for each database servers, but by default the
helper utility class will use the hibernate.cfg.xml file located in the root location.
If you expand the Libraries node in the Projects window you can see that the IDE added the required
1. Open hibernate.cfg.xml in the Design tab. You can open the file by expanding the
Click OK. This enables the debug logging of the SQL statements.
If you click the XML tab in the editor you can see the file in XML view. Your file should look like
the following:
<hibernate-configuration>
<session-factory name="session1">
<property
name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property
name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property
>
<property
name="hibernate.connection.url">jdbc:mysql://localhost:3306/sakila</prop
erty>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">######</property>
<property name="hibernate.show_sql">true</property>
</session-factory>
</hibernate-configuration>
5. Save your changes to the file.
When you run your project you will be able to see the SQL query printed in the IDE's Output window.
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.
1. Right-click the Source Packages node and select New > Other to open the New File wizard.
2. Select Hibernate from the Categories list and HibernateUtil.java from the File Types list.
Click Next.
3. Type HibernateUtil for the class name and sakila.util as the package name. Click Finish.
When you click Finish, HibernateUtil.java opens in the editor. You can close the file because you do not
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
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.
Notes.
• If you are using NetBeans IDE 6.5, you do not need to create the hibernate.reveng file with the
Reverse Engineering wizard. You create the reverse engineering file and specify the database tables in
• 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.
default settings used when generating Hibernate files from the metadata of the database specified in
hibernate.cfg.xml. The wizard generates the file with basic default settings. You can modify the file to
explicitly specify the database schema that is used, to filter out tables that should not be used and to specify
1. Right-click the Source Packages node and select New > Other to open the New File wizard.
2. Select Hibernate from the Categories list and Hibernate Reverse Engineering Wizard from
5. Select actor in the Available Tables pane and click Add. Click Finish.
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.
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
1. Right-click the Source Packages node in the Projects window and choose New > Other to
2. Select Hibernate Mapping Files and POJOs from a Database in the Hibernate category. Click
Next.
3. Select hibernate.cfg.xml from the Hibernate Configuration File dropdown list, if not
selected.
5. Ensure that the Domain Code and Hibernate XML Mappings options are selected.
When you click Finish, the IDE generates the POJO Actor.java with all the required fields and generates a
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.
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
2. Select JFrame Form from the Swing GUI Forms category. Click Next.
3. Type DVDStoreAdmin for the Class Name and type sakila.ui for the Package. Click Finish.
When you click Finish the IDE create the class and opens the JFrame Form in the Design view of the editor.
Palette appears in the left 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
1. Drag a Label element from the Palette and change the text to Actor Profile.
2. Drag a Label element from the Palette and change the text to First Name.
3. Drag a Text Field element next to the First Name label and delete the default text.
4. Drag a Label element from the Palette and change the text to Last Name.
5. Drag a Text Field element next to the Last Name label and delete the default text.
6. Drag a Button element from the Palette and change the text to Query.
8. Modify the Variable Name values of the following UI elements according to the values in the
following table.
You can modify the Variable Name value of an element by right-clicking the element in the
Design view and then choosing Change Variable Name. Alternatively, you can change the
You do not need to assign Variable Name values to the Label elements.
Table resultTable
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.
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.
1. Expand the <default package> source package node in the Projects window.
2. Right-click hibernate.cfg.xml and choose Run HQL Query to open the HQL Editor.
3. Test the connection by typing from Actor in the HQL Query Editor. Click the Run HQL
When you click Run HQL Query you should see the query results in the bottom pane of the HQL
Query Editor.
If you click the SQL button above the results you should see the following equivalent SQL
query.
select actor0_.actor_id as col_0_0_ from sakila.actor actor0_
4. Type the following query in the HQL Query Editor and click Run HQL Query to check the
5. Open a new HQL Query Editor tab and type the following query in the editor pane. Click Run
HQL Query.
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.
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.
3. public DVDStoreAdmin() {
4. initComponents();
5. }
6.
7. private static String QUERY_BASED_ON_FIRST_NAME="from Actor a
where a.firstName like '";
private static String QUERY_BASED_ON_LAST_NAME="from Actor a where
a.lastName like '";
It is possible to copy the queries from the HQL Query Editor tabs into the file and then modify
the code.
8. Add the following methods to create the query based on the user input string.
makes use of the HibernateUtil.java utility class to obtain the Hibernate Session.
27. Fix your imports to add import statements for the Hibernate libraries
28. Create a Query button event handler by switching to the Design view and double-clicking
The IDE creates the queryButtonActionPerformed method and displays the method in the
Source view.
29. Modify the queryButtonActionPerformed method in the Source view by adding
the following code so that a query is run when the user clicks the button.
31. if(!firstNameTextField.getText().trim().equals("")) {
32. runQueryBasedOnFirstName();
33. } else if(!lastNameTextField.getText().trim().equals("")) {
34. runQueryBasedOnLastName();
35. }
}
36. Add the following method to display the results in the JTable.
55. Fix your imports to add java.util.Vector and save your changes.
After you save the form you can run the project.
specify the application's Main Class in the project's properties dialog box. If no Main Class is specified, you
are prompted to set it the first time that you run the application.
1. Right-click the project node in the Projects window and choose Properties.
Alternatively, you can click the Browse button and choose the main class in the dialog box.
4. Click Run Main Project in the main toolbar to 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
• Checkout the project sources from the NetBeans Samples by performing the following steps:
1. Choose Team > Subversion > Checkout from the main menu.
https://svn.netbeans.org/svn/samples~samples-source-code
Click Next.
5. Specify the Local Folder for the sources (the local folder must be empty).
6. Click Finish.
When you click Finish, the IDE initializes the local folder as a Subversion repository and checks
7. Click Open Project in the dialog that appears when checkout is complete.
Notes.
o Steps for checking out sources from Kenai only apply to NetBeans IDE 6.7 and 6.8.
o You need a Subversion client to checkout the sources from Kenai. For more about installing
Subversion, see the section on Setting up Subversion in the Guide to Subversion in NetBeans IDE.
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
Note. This exercise is optional and describes how to create the POJO and mapping file that you created with
1. Right-click the Source Packages node in the Projects window and choose New > Java Class
2. In the wizard, type Actor for the class name and type sakila.entity for the package. Click
Finish.
3. Make the following changes (displayed in bold) to the class to implement the Serializable
Generate.
In the Generate Getters and Setters dialog box, you can use the Up arrow on the keyboard to
move the selected item to the Actor node and then press the Space bar to select all fields in
Actor.
After you create the POJO for the table you will want to create an Hibernate Mapping File for Actor.java.
1. Right-click the sakila.entity source packages node in the Projects window and choose
3. Type Actor.hbm for the File Name and check that the Folder is src/sakila/entity. Click
Next.
4. Type sakila.entity.Actor for the Class to Map and select actor from the Database Table
When you click Finish the Actor.hbm.xml Hibernate mapping file opens in the source editor.
The IDE also automatically adds an entry for the mapping resource to hibernate.cfg.xml.
You can view the entry details by expanding the Mapping node in the Design view of
hibernate.cfg.xml or in the XML view. The mapping entry in the XML view will look like the
following:
<mapping resource="sakila/entity/Actor.hbm.xml"/>
</session-factory>
</hibernate-configuration>
5. Map the fields in Actor.java to the columns in the ACTOR table by making the following
6. <hibernate-mapping>
file.
Note: By default, the generated class element has a closing tag. Because you need to add
property elements between the opening and closing class element tags, you need to make the
following changes (displayed in bold). After making the changes you can then use code
<hibernate-mapping>
<class name="sakila.entity.Actor" table="actor">
</class>
</hibernate-mapping>
22. Click the Validate XML button in the toolbar and save your changes.
Creating individual POJOs and Hibernate mapping files might be a convenient way to further customizing
your application.
See Also
For additional information on creating Swing GUI applications, see the following tutorials.