Creating a Maven Swing Application Using Hibernate - NetBeans IDE Tutorial

This tutorial needs a review. You can edit it in GitHub following these contribution guidelines.

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.

Software or Resource Version Required


version 2.09 or newer

MySQL database server

version 5.x

Sakila Database

plugin available from update center

Before starting this tutorial you may want to familiarize yourself with the following documentation.

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.

  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.

  3. Right-click the MySQL Server node and choose Create Database.

  4. Select the Sakila database from the New Database Name drop down list in the Create MySQL Database dialog box. Click OK.

create sakila mysql
Figure 1. Screenshot of Create MySQL Database dialog

When you click OK the IDE will run a script to create the Sakila database and populate the database tables. You can see the results of running the script in the Output window. A node for the Sakila database is also added under the MySQL Server node.

  1. Right-click the Sakila node and choose Connect.

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.

Configuring Maven

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.

  1. Open the Options window in the IDE (Tools > Options; NetBeans > Preferences on Mac).

  2. Select the Java category in the Options window and click the Maven tab.

  3. Confirm that a Maven Home is specified.

You can use the Maven version bundled with the IDE or specify the location of a local Maven installation (requires 2.0.9 or newer).

  1. Click OK to close the Options window.


  • Maven support is automatically enabled when Java is enabled in the IDE. You will need to enable the Java EE plugin if it is not enabled.

  • In NetBeans IDE 7.1 and earlier versions of the IDE, the Maven tab in the Options window is located in the Miscellaneous category.

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.

  1. Choose Window > Services to open the Services window.

  2. Expand the Maven Repositories node in the Services window to view the repositories.

  3. Expand a repository node to view the artifacts.

  4. Right-click a repository node and choose Update Index in the popup menu to update the repository.

maven repositories
Figure 2. Maven Repositories in Services window

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.

For more about managing Maven classpath dependencies and working with Maven repositories in the IDE, see the Dependency Management section of Best Practices for Apache Maven in NetBeans IDE.

Notes for NetBeans IDE 7.1 and earlier versions of the IDE.

  • Choose Window > Other > Maven Repositories Browser to view Maven repositories.

  • You can use the buttons in the toolbar of the Maven Repositories Browser to update indexes and search for artifacts.

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.

  1. Choose File > New Project (Ctrl-Shift-N; ⌘-Shift-N on Mac) from the main menu to open the New Project wizard.

  2. Select Java Application from the Maven category. Click Next.

maven project wizard
Figure 3. Maven Archetypes in New Project wizard
  1. Type DVDStoreAdmin for the project name and set the project location.

  2. Modify the default Group Id and Version (optional).

The Group Id and Version will be used as the coordinates for the artifact in your local repository when you build the project.

  1. Click Finish.

When you click finish the IDE creates the Maven project and opens the project in the Projects window. The IDE automatically creates the class in the com.mycompany.dvdstoreadmin package. You can delete 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.

  1. Right-click the project node and choose Properties.

  2. Select the Sources category in the Properties window.

  3. Confirm that the Source/Binary Format that is selected in the drop-down list is 1.5 or higher.

  4. Select UTF-8 from the drop-down list for the Encoding property. Click OK.

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.

  1. Right-click the Sakila database connection in the Services window and choose Connect.

  2. Right-click the Source Packages node in the Projects window and choose New > Other to open the New File wizard.

  3. Select Hibernate Configuration Wizard from the Hibernate category. Click Next.

  4. Keep the default file name ( hibernate.cfg ).

  5. Click Browse and specify the src/main/resources directory as the Location (if not already specified). Click Next.

  6. Select the sakila connection in the Database Connection drop down list. Click Finish.

hib config
Figure 4. Dialog for selecting database connection

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).

maven project libs
Figure 5. Dependencies under Libraries node in Projects window

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.

maven artifacts viewer
Figure 6. Graphs tab or Artifact Viewer showing dependencies

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.

  1. Open hibernate.cfg.xml in the Design tab. You can open the file by expanding the Configuration Files node in the Projects window and double-clicking hibernate.cfg.xml .

  2. Expand the Configuration Properties node under Optional Properties.

  3. Click Add to open the Add Hibernate Property dialog box.

  4. In the dialog box, select the hibernate.show_sql property and set the value to true . Click OK. This enables the debug logging of the SQL statements.

add property showsql
Figure 7. Add Hibernate Property dialog box showing setting value for the hibernate.show_sql property
  1. Click Add under the Miscellaneous Properties node and select hibernate.query.factory_class in the Property Name dropdown list.

  2. Type org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory in the text field. Click OK.

Note. Do not select the value from the drop-down list.

add property factoryclass 4
Figure 8. Add Hibernate Property dialog box showing setting value for the hibernate.query.factory_class property

If you click the XML tab in the editor you can see the file in XML view. Your file should look similar to the following:

    <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</property>
        <property name="hibernate.connection.username">root</property>
        <property name="hibernate.connection.password">######</property>
        <property name="hibernate.show_sql">true</property>
        <property name="hibernate.query.factory_class">org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory</property>
  1. 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.

Creating the 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 .

  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 from the File Types list. Click Next.

  3. Type HibernateUtil for the class name and sakila.util as the package name. Click Finish.

maven hibutil wizard
Figure 9. Hibernate Util wizard

When you click Finish, 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), , 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 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 .

  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 the File Types list. Click Next.

  3. Type hibernate.reveng for the file name.

  4. Specify src/main/resources as the Location. Click Next.

  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.

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).

  1. Right-click the Source Packages node in the Projects window and choose New > Other to open the New File wizard.

  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.

  4. Select hibernate.reveng.xml from the Hibernate Reverse Engineering File dropdown list, if not selected.

  5. Ensure that the Domain Code and Hibernate XML Mappings options are selected.

  6. Type sakila.entity for the Package name. Click Finish.

mapping pojos wizard
Figure 10. Generate Hibernate Mapping Files and POJOs wizard

When you click Finish, the IDE generates the POJO 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

  1. Right-click the project node in the Projects window and choose New > Other to open the New File wizard.

  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 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.

  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.

When you delete the default text, the text field will collapse. You can resize the text field later to adjust the alignment of the form elements.

  1. Drag a Label element from the Palette and change the text to Last Name.

  2. Drag a Text Field element next to the Last Name label and delete the default text.

  3. Drag a Button element from the Palette and change the text to Query.

  4. Drag a Table element from the Palette into the form.

  5. 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 Variable Name directly in the Inspector window.

You do not need to assign Variable Name values to the Label elements.

Element Variable Name

First Name text field


Last Name text field


Query button




  1. Resize the text fields and align the form elements.

You can enable the Horizontal Resizable property for the text fields to ensure that the text fields resize with the window and that the spacing between elements remains constant.

  1. Save your changes.

In Design view your form should look similar to the following image.

hib jframe form
Figure 11. GUI form in Design view of the editor

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.

  1. Right-click the project node and choose Build.

When you click Build, the IDE will download the necessary artifacts to your local Maven repository.

  1. Expand the <default package> source package node under the Other Sources 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 Query button ( run hql query 16 ) in the toolbar.

When you click Run HQL Query you should see the query results in the bottom pane of the HQL Query Editor.

hib query hqlresults
Figure 12. HQL Query Editor showing HQL query results
  1. Type the following query in the HQL Query Editor and click Run HQL Query to check the query results when the search string is 'PE'.

from Actor a where a.firstName like 'PE%'

The query returns a list of actors' details for those actors whose first names begin with 'PE'.

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 actor0_ where (actor0_.first_name like 'PE%' )
  1. Open a new HQL Query Editor tab and type the following query in the editor pane. Click Run HQL Query.

from Actor a where a.lastName like 'MO%'

The query returns a list of actors' details for those actors whose last names begin with 'MO'.

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 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.

  1. Open and click the Source tab.

  2. Add the following query strings (in bold) to the class.

public DVDStoreAdmin() {

*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.

  1. Add the following methods to create the query based on the user input string.

private void runQueryBasedOnFirstName() {
    executeHQLQuery(QUERY_BASED_ON_FIRST_NAME + firstNameTextField.getText() + "%'");

private void runQueryBasedOnLastName() {
    executeHQLQuery(QUERY_BASED_ON_LAST_NAME + lastNameTextField.getText() + "%'");

The methods call a method called executeHQLQuery() and create the query by combining the query string with the user entered search string.

  1. Add the executeHQLQuery() method.

private void executeHQLQuery(String hql) {
    try {
        Session session = HibernateUtil.getSessionFactory().openSession();
        Query q = session.createQuery(hql);
        List resultList = q.list();
    } catch (HibernateException he) {

The executeHQLQuery() method calls Hibernate to execute the selected query. This method makes use of the utility class to obtain the Hibernate Session.

  1. Fix your imports to add import statements for the Hibernate libraries ( org.hibernate.Query , org.hibernate.Session ) and java.util.List .

  2. Create a Query button event handler by switching to the Design view and double-clicking the Query button.

The IDE creates the queryButtonActionPerformed method and displays the method in the Source view.

  1. 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.

private void queryButtonActionPerformed(java.awt.event.ActionEvent evt) {
    *if(!firstNameTextField.getText().trim().equals("")) {
    } else if(!lastNameTextField.getText().trim().equals("")) {
  1. Add the following method to display the results in the JTable.

private void displayResult(List resultList) {
    Vector<String> tableHeaders = new Vector<String>();
    Vector tableData = new Vector();

    for(Object o : resultList) {
        Actor actor = (Actor)o;
        Vector<Object> oneRow = new Vector<Object>();
    resultTable.setModel(new DefaultTableModel(tableData, tableHeaders));
  1. Fix your imports (Ctrl+Shift+I) to add java.util.Vector and save your changes.

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.


  • Building and running a project for the first time can take some time if the IDE needs to checkout any project dependencies. Subsequent builds will be much faster.

  • To run this application, you first need to specify the Main Class.

To compile and launch this application, perform the following tasks.

  1. Right-click the project node in the Projects window and choose Properties.

  2. Select the Run category in the Project Properties dialog box.

  3. Type sakila.ui.DVDStoreAdmin for the Main Class. Click OK.

Alternatively, you can click the Browse button and choose the main class in the dialog box.

browse main class
Figure 13. Setting the main class in the Browse Main Classes dialog
  1. Click Run Project in the main toolbar to launch the application.

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

maven projectproperties
Figure 14. Actions pane of DVDStoreAdmin project 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.

application run
Figure 15. DVDStoreAdmin application showing results

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.

  • Download a zip archive of the finished project.

  • Checkout the project sources from the NetBeans Samples by performing the following steps:

    1. Choose Team > Subversion > Checkout from the main menu.

    2. In the Checkout dialog box, enter the following Repository URL: Click Next.

      1. Click Browse to open the Browse Repostiory Folders dialog box.

      2. Expand the root node and select samples/java/DVDStoreAdmin-Maven. Click OK.

      3. Specify the Local Folder for the sources (the local folder must be empty).

      4. Click Finish.

When you click Finish, the IDE initializes the local folder as a Subversion repository and checks out the project sources.

  1. Click Open Project in the dialog that appears when checkout is complete.


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.

  1. Right-click the Source Packages node in the Projects window and choose New > Java Class to open the New Java Class wizard.

  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 interface and add fields for the table columns.

public class Actor *implements Serializable* {
    *private Short actorId;
    private String firstName;
    private String lastName;
    private Date lastUpdate;*
  1. Generate the getters and setters for the fields by placing the insertion cursor in the source editor, typing Alt-Insert and then selecting Getter and Setter.

  2. In the Generate Getters and Setters dialog box, select all the fields and click Generate.

getters setters
Figure 16. Generate Getters and Setters dialog box

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.

  1. Fix your imports and save your changes.

After you create the POJO for the table you will want to create an Hibernate Mapping File for .

  1. Right-click the sakila.entity source packages node in the Projects window and choose New > Other to open the New File wizard.

  2. Select Hibernate Mapping Wizard in the Hibernate category. Click Next.

  3. Type Actor.hbm for the File Name and set the Folder to src/main/resources/sakila/entity . Click Next.

  4. Type sakila.entity.Actor for the Class to Map.

  5. Select actor from the Database Table drop down list if not already selected. Click Finish.

mapping wizard
Figure 17. Generate Hibernate Mapping Files wizard

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"/>
  1. Map the fields in to the columns in the ACTOR table by making the following changes (in bold) to Actor.hbm.xml .

  <class name="sakila.entity.Actor" *table="actor">
    <id name="actorId" type="java.lang.Short">
      <column name="actor_id"/>
      <generator class="identity"/>
    <property name="firstName" type="string">
      <column length="45" name="first_name" not-null="true"/>
    <property name="lastName" type="string">
      <column length="45" name="last_name" not-null="true"/>
    <property name="lastUpdate" type="timestamp">
      <column length="19" name="last_update" not-null="true"/>

You can use code completion in the editor to complete the values when modifying the mapping file.

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 completion between the class tags.
  <class name="sakila.entity.Actor" *table="actor">
  1. 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 customize your application.