Chuyển tới nội dung
Home » Hibernate Web Application Example In Netbeans | Creating The Filmhelper.Java Helper Class

Hibernate Web Application Example In Netbeans | Creating The Filmhelper.Java Helper Class

#14. JSP Servlet Hibernate CRUD Example

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.

When you click OK a Sakila node appears 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.

Using Hibernate in a Web Application

This tutorial needs a review. You can edit it in GitHub following these contribution guidelines.
  • Creating the Database
  • Creating the Web Application Project
  • Modifying the Hibernate Configuration File
  • Creating the

    HibernateUtil.java

    Helper File
  • Generating Hibernate Mapping Files and Java Classes
  • Creating the

    FilmHelper.java

    Helper Class
  • Creating the JSF Managed Bean
  • Creating the Web Pages
  • Running the Project
  • See Also

In this tutorial, you use the NetBeans IDE to create and deploy a web application that displays data from a database. The web application uses the Hibernate framework as the persistence layer for retrieving and storing plain old Java objects (POJOs) to a relational database.

Hibernate is framework that provides tools for object relational mapping (ORM). The tutorial demonstrates how to add support for the Hibernate framework to the IDE and create the necessary Hibernate files. After creating the Java objects and configuring the application to use Hibernate, you create a JSF managed bean and JSF 2.0 pages to display the data.

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

  • Hibernate documentation at hibernate.org

To follow this tutorial, you need the following software and resources.

Software or Resource Version Required

7.1, 7.2, 7.3, 7.4, Java EE version

Version 6 or 7

GlassFish Server Open Source Edition

3.x or 4.x

Version 5.x

Sakila Database

Plugin available from update center

You can download a zip archive of the finished project.

#14. JSP Servlet Hibernate CRUD Example
#14. JSP Servlet Hibernate CRUD Example

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.

Notes.

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

Creating the Reverse Engineering File

The reverse engineering file (

hibernate.reveng.xml

) is an XML file that can be used to modify the 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 how JDBC types are mapped to Hibernate types.

  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. Keep the default *


    src

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

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.

When you click Finish, the IDE generates the POJO

Actor.java

with all the required fields and generates a Hibernate mapping file 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.

Running the Project

Now that the coding is finished, you can launch the application. Before you run the project, you need to 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.

  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.

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

  • 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:


      https://svn.netbeans.org/svn/samples~samples-source-code

      Click Next.

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

      2. Expand the root node and select samples/java/DVDStoreAdmin-Ant. 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.

Note. You need a Subversion client to checkout the sources. For more about installing Subversion, see the section on Setting up Subversion in the Guide to Subversion in NetBeans IDE.

How to Setting Up Hibernate in NetBeans IDE | Java Hibernate Tutorial #Ep01 (2020)
How to Setting Up Hibernate in NetBeans IDE | Java Hibernate Tutorial #Ep01 (2020)

Creating the Java Swing Application Project

In this exercise you create a simple Java Swing application project called DVDStoreAdmin.

  1. Choose File > New Project (Ctrl-Shift-N). Select Java Application from the Java category and click Next.

  2. Type DVDStoreAdmin for the project name and set the project location.

  3. Deselect the Use Dedicated Folder option, if selected. For this tutorial there is little reason to copy project libraries to a dedicated folder because you will not need to share libraries with other users.

    1. Deselect Create Main Class. Click Finish.

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.

Preparing the Hibernate Front End to the Database

It is good practice to segregate the Hibernate code that accesses the database into a separate project. The

HibernateTravelPOJO.zip

file contains the HibernateTravelPOJO project, which is a Hibernate front end for accessing the
Travel database.
You can import HibernateTravelPOJO as a library dependency into any
Visual Web project to enable that project to access the Travel database through Hibernate’s mappings. The HibernateTravelPOJO project contains the required mapping file, configuration file, utility class, and POJO persistent classes, as described in Introduction to Hibernate. The following figure shows the project’s contents.

Figure 2: Contents of the HibernateTravelPOJO Project

Note: For simplicity, the HibernateTravelPOJO is a subset of a full front end for the Travel database and only contains the classes, properties, and relationships that are necessary for the tutorial project.

  1. Extract the contents of the
    HibernateTravelPOJO.zip file into the

    NetBeansProjects

    folder under your home directory, or into directory of your choice.
  2. In the IDE, close any open projects.
  3. Choose File > Open Project, and open the HibernateTravelPOJO project.
  4. In the Projects window, expand the HibernateTravelPOJO node, right-click the Libraries node, and choose Add Library from the pop-up menu.
  5. In the Add Library dialog box, select Hibernate322 and click Add Library.
  6. Right-click the Libraries node again, and choose Add JAR/Folder from the pop-up menu.
  7. Navigate to and select the JavaDB network client

    derbyclient.jar

    for the Travel database’s server. With a typical Visual
    Web Pack installation,
    this JAR file is in
    Sun-Java-Application-Server-Install-Dir

    /javadb/lib/derbyclient.jar

    If you are using a different database server, navigate to and
    select that server’s client.

  8. Press Enter.

    The database driver is now available for Hibernate connections to the database.

  9. If you are using a different port number than the default port number of 1527, or if you are using a different database, edit the

    hibernate.connection.url

    property in the HibernateTravelPOJO > Source Packages > default packages >

    hibernate.cfg.xml

    configuration file.

    To determine the port number for your database, look in the
    Runtime window for the jdbc node for the Travel database.
    The port number follows the host name.
    If the Travel database is not available, see the Configuration Information section in the NetBeans Visual Web Pack Installation Instructions for information.

  10. In the Projects window, right-click the HibernateTravelPOJO node and choose Build Project.
Hibernate  CRUD Project Step by Step
Hibernate CRUD Project Step by Step

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

  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.

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

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

Table

  1. Save your changes.

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 a Web Project That Uses the Hibernate Framework

In this section, you create a Visual Web project and add the HibernateTravelPOJO Java class project to the web project. The following figure shows the web page that you build in this project.

Figure 3: HibernateTutorialApp Page1
  1. In the Runtime window, expand the Databases node.
  2. Right-click the jdbc node for the Travel database and choose Connect
    from the pop-up menu.
  3. In the Connect dialog box, enter

    travel

    for the Password,
    select Remember Password During This Session, and click OK.
  4. From the main menu, choose File > New Project.
  5. In the New Project Wizard, select Web from the Categories list and select
    Visual Web Application from the Projects list.
  6. Click Next.
  7. Name the project

    HibernateTutorialApp

    , select
    the Server and Java EE Version, and click Finish.

    Your project appears with the initial page (

    Page1

    ) open in the Visual Designer.

  8. In the Projects window, right-click HibernateTutorialApp > Libraries and choose Add Library.
  9. In the Add Library window, select Hibernate322 and click Add Library, as shown in the following figure.

    Figure 4: Adding the Hibernate Library
  10. Right-click HibernateTutorialApp > Libraries again,
    and choose Add Project.
  11. In the Add Project window, navigate to and choose HibernateTravelPOJO, and click Add Project JAR Files, as shown in the following figure.

    Figure 5: Adding the HibernateTravelPOJO Project
  12. Drag a Drop Down List component from the Palette and drop it in the top left corner of Page1 in the Visual Designer.
  13. Double-click the Drop Down List component that you
    just added to Page1.

    The IDE adds a method for processing a change in the drop-down list selection
    and displays the method in the source editor. The IDE also registers
    the method as a handler for the value change event.
    You add code to this method later.

  14. Click Design in the editing toolbar to switch back to the Visual
    Designer.
  15. Right-click the Drop Down List component and select Auto-Submit on Change from the pop-up menu.

    This action causes the browser to submit the page whenever the user chooses a new value from the drop-down list.

  16. Drag and drop a Message Group component to the right of the Drop Down List component.

    Message Group components help you to diagnose runtime problems.

  17. Drag and drop a Table component below the Drop Down List component.
Hibernate with NetBeans
Hibernate with NetBeans

Preparing the Hibernate Front End to the Database

It is good practice to segregate the Hibernate code that accesses the database into a separate project. The

HibernateTravelPOJO.zip

file contains the HibernateTravelPOJO project, which is a Hibernate front end for accessing the
Travel database.
You can import HibernateTravelPOJO as a library dependency into any
Visual Web project to enable that project to access the Travel database through Hibernate’s mappings. The HibernateTravelPOJO project contains the required mapping file, configuration file, utility class, and POJO persistent classes, as described in Introduction to Hibernate. The following figure shows the project’s contents.

Figure 2: Contents of the HibernateTravelPOJO Project

Note: For simplicity, the HibernateTravelPOJO is a subset of a full front end for the Travel database and only contains the classes, properties, and relationships that are necessary for the tutorial project.

  1. Extract the contents of the
    HibernateTravelPOJO.zip file into the

    NetBeansProjects

    folder under your home directory, or into directory of your choice.
  2. In the IDE, close any open projects.
  3. Choose File > Open Project, and open the HibernateTravelPOJO project.
  4. In the Projects window, expand the HibernateTravelPOJO node, right-click the Libraries node, and choose Add Library from the pop-up menu.
  5. In the Add Library dialog box, select Hibernate322 and click Add Library.
  6. Right-click the Libraries node again, and choose Add JAR/Folder from the pop-up menu.
  7. Navigate to and select the JavaDB network client

    derbyclient.jar

    for the Travel database’s server. With a typical Visual
    Web Pack installation,
    this JAR file is in
    Sun-Java-Application-Server-Install-Dir

    /javadb/lib/derbyclient.jar

    If you are using a different database server, navigate to and
    select that server’s client.

  8. Press Enter.

    The database driver is now available for Hibernate connections to the database.

  9. If you are using a different port number than the default port number of 1527, or if you are using a different database, edit the

    hibernate.connection.url

    property in the HibernateTravelPOJO > Source Packages > default packages >

    hibernate.cfg.xml

    configuration file.

    To determine the port number for your database, look in the
    Runtime window for the jdbc node for the Travel database.
    The port number follows the host name.
    If the Travel database is not available, see the Configuration Information section in the NetBeans Visual Web Pack Installation Instructions for information.

  10. In the Projects window, right-click the HibernateTravelPOJO node and choose Build Project.

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 Library dialog box.

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.

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 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 open the New File wizard.

  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


    src

    directory). Click Next.

  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 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 Hibernate JAR files and the MySQL connector JAR.

Note. NetBeans IDE 8.0 bundles the Hibernate 4 libraries. Older versions of the IDE bundled Hibernate 3.

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.

  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.

  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 as the Property Value.

This is the translator factory class that is used in Hibernate 4 that is bundled with the IDE.

Click OK.

If you are using NetBeans IDE 7.4 or earlier you should select org.hibernate.hql.classic.ClassicQueryTranslatorFactory as the Property Value in the dialog box. NetBeans IDE 7.4 and earlier bundled Hibernate 3.

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



org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/sakila root ###### true org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory

  1. Save your changes to the file.

After you create the form and set it as the main class you will be able to see the SQL query printed in the IDE’s Output window when you run the project.

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

.

  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.

  1. 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 need to edit the file.

Java Simple Project step by step using mysql database
Java Simple Project step by step using mysql database

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

  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.

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

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

Table

  1. Save your changes.

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.

Hibernate and JPAJDBC

Java Database Connectivity (JDBC) is an API packaged with the Java SE edition that makes it possible to standardize and simplify the process of connecting Java applications to external, relational database management systems (RDBMS).

Fundamentally, applications written in Java perform logic. The Java language provides facilities for performing iterative logic with looks, conditional logic with if statements and object-oriented analysis through the use of classes and interfaces. But Java applications do not store data persistently.

Data persistence is typically delegated to NoSQL databases such as MongoDB and Cassandra, or to relational databases such as IBM’s DB2 or Microsoft’s SQL Server or the popular open source database MySQL.

To help address the object-relational impedance mismatch, a number of frameworks exist that simplify the task of moving data between a relational database and a Java program. Popular object-relational mapping (ORM) frameworks include Hibernate, TopLink and DataNucleus. While each framework has its own set of unique capabilities, all of them comply with the Java Persistence API standard, which is now part of the Java EE/Jakarta EE specification.

Spring Boot Simple Project step by step using Mysql Database
Spring Boot Simple Project step by step using Mysql Database

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. Right-click in the editor and choose Insert Code (Alt-Insert; Ctrl-I on Mac) and select Getter and Setter in the popup menu to generate getters and setters for the fields.

  2. In the Generate Getters and Setters dialog box, select all the fields and click 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.

  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

Actor.java

.

  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 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 drop down list. Click Finish.

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:

  1. Map the fields in


    Actor.java

    to the columns in the ACTOR table by making the following changes (in bold) to

    Actor.hbm.xml

    .

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

By default, the generated
  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 customizing your application.

Running the Project

The basics of the application are now complete. You can now run the application to check if everything is working correctly.

  1. Click Run Main Project in the main toolbar or right-click the DVDStore application node in the Projects window and choose Run.

The IDE saves all changed files, builds the application, and deploys the application to the server. The IDE opens a browser window to the URL

http://localhost:8080/DVDStore/

that displays the list of films.

  1. In your browser, click “View” to load


    browse.xhtml

    to view the film details.

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:


      https://svn.netbeans.org/svn/samples~samples-source-code

      Click Next.

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

      2. Expand the root node and select samples/javaee/DVDStoreEE6. Click OK.

      3. Specify the Local Folder for the sources.

      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.

Notes. For more about installing Subversion, see the section on Setting up Subversion in the Guide to Subversion in NetBeans IDE.

Troubleshooting

Most of the problems that occur with the tutorial application are due to communication difficulties between the GlassFish Server Open Source Edition and the MySQL database server. If your application does not display correctly, or if you are receiving a server error, you might want to look at the Troubleshooting section of the Creating a Simple Web Application Using a MySQL Database tutorial or the Connecting to a MySQL Database tutorial.

If you download and run the solution project you might see the following error in the Output window if it is the first time that you have deployed an application that uses the MySQL database.


SEVERE: JDBC Driver class not found: com.mysql.jdbc.Driver java.lang.ClassNotFoundException: com.mysql.jdbc.Driver at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1509) [...] at java.lang.Thread.run(Thread.java:680) SEVERE: Initial SessionFactory creation failed.org.hibernate.HibernateException: JDBC Driver class not found: com.mysql.jdbc.Driver INFO: cleaning up connection pool: null INFO: Domain Pinged: stable.glassfish.org

In your browser window you might see a

java.lang.ExceptionInInitializerError

and the following stack trace.


java.lang.ExceptionInInitializerError at dvdrental.HibernateUtil.

(HibernateUtil.java:28) ... Caused by: org.hibernate.HibernateException: JDBC Driver class not found: com.mysql.jdbc.Driver ... Caused by: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver ...

The output message states that the JDBC driver for the MySQL database was not found. The most probable reason is that you need to add the MySQL JDBC driver file to your GlassFish server installation. To confirm that the driver is missing, navigate to the

GLASSFISH-INSTALL/glassfish/domains/domain1/lib

directory on your local system (where GLASSFISH-INSTALL is your GlassFish installation directory). If the

domain1/lib

directory does not contain the JDBC driver file (for example,

mysql-connector-java-5.1.13-bin.jar

) you need to copy the JDBC driver to the directory. The MySQL JDBC driver is not added to your GlassFish installation when you install the server.

You can add a copy of the MySQL JDBC driver to your GlassFish installation by performing the following steps.

  1. Download the MySQL Connector/J JDBC driver.

  2. Extract the driver and copy the driver file (for example,


    mysql-connector-java-5.1.13-bin.jar

    ) to the

    domain1/lib

    directory of your GlassFish installation.

Alternatively, when you use the IDE to create an application that uses the MySQL database, the IDE can automatically copy the bundled MySQL JDBC driver to the GlassFish server when you deploy the project, if required. To confirm that the IDE will copy the necessary JDBC drivers, choose Tools > Servers from the main menu to open the Servers manager and confirm that the Enable JDBC Driver Deployment option is selected for your GlassFish server.

After you create and deploy a web application that uses the MySQL database, if you navigate to the

domain1/lib

directory of your local GlassFish installation you will see that directory contains the JDBC driver file.

>> More Visual Web Pack Documentation

Using Hibernate With the NetBeans Visual Web Pack

Contributed by Chris
Kutler, Craig McClananan, and John Baker

May [Revision number: V5.5.1-1]

This tutorial shows you how to use the Hibernate framework in a NetBeans Visual Web Pack project. It also shows how to wrap
back end data with Option arrays and ObjectListDataProvider
objects for binding to JavaServer Faces components.

Examples used in this tutorial

» HibernateTravelPOJO.zip

This tutorial works with the following technologies and resources

JavaServer Faces Components/
Java EE Platform
1.2 with Java EE 5*1.1 with J2EE 1.4
Travel Database Required
BluePrints AJAX Component Library Not required

* As of the date this tutorial was published, only the Sun Java System Application Server supported Java EE 5.

This tutorial has been tailored for use with the Sun Java Application Server PE 9.0 Update Release 1 and with Tomcat 5.5.17.
If you are using a different server, consult the Release Notes and FAQs for known problems and workarounds.
For detailed information about the
supported servers and Java EE platform, see the Release Notes.

Senior Programmers vs Junior Developers #shorts
Senior Programmers vs Junior Developers #shorts

Adding the Object List Data Provider Wrapper for the Trips List

In this section you extend the

ObjectListDataProvider

class to build a

TripDataProvider

wrapper for the results from a trips query.

  1. In the Projects window, right-click HibernateTutorialApp >
    Source Packages > hibernatetutorialapp and choose New > Java Class.
  2. Name the class

    TripDataProvider

    and click Finish.

    A TripDataProvider.java node appears under the hibernatetutorialapp package node and the IDE displays the source code for the

    TripDataProvider

    class.

  3. Replace the class definition with the following code.

    Code Sample 2:

    TripDataProvider

    Class

    public class TripDataProvider extends ObjectListDataProvider{
    private ArrayList tripsList = new ArrayList();
    // Note: to eliminate warnings when using Java SE 1.5, use instead
    // private ArrayList
    tripsList = new ArrayList
    ();
    /** Creates a new instance of tripDataProvider */
    public TripDataProvider() {
    // Put in dummy data for design time
    tripsList.add(new Trip());
    // Wrap the list
    setList(tripsList);
    }
    public void refreshTripsList(Integer personId){
    tripsList.clear();
    try{
    Session session =
    HibernateUtil.getSessionFactory().getCurrentSession();
    Transaction tx = session.beginTransaction();
    Person person =
    (Person)
    session.load(Person.class, personId);
    Set personTrips = (PersistentSet)person.getTrips();
    tripsList.addAll(personTrips);
    tx.commit();
    } catch(Exception e){
    e.printStackTrace();
    }
    }
    }

  4. Right-click in the source and choose Fix Imports from the pop-up menu.
  5. Select the following fully qualified names, and click OK.

    Class Name Fully Qualified Name

    Session

    org.hibernate.Session

    Transaction

    org.hibernate.Transaction

    Set

    java.util.Set
  6. Close and save the file.
  7. In the Outline window, right-click the SessionBean1 node and choose Add > Property from the pop-up menu.
  8. In the New Property Pattern dialog box, type

    tripDataProvider

    in the Name text box, type

    TripDataProvider

    in the Type text box, and click OK.
  9. Double-click the SessionBean1 node to open the

    SessionBean1.java

    source file.
  10. In the Navigation window, double-click the tripDataProvider node.

    The IDE scrolls the source code to the declaration for the tripDataProvider property.

  11. Replace the declaration for the

    tripDataProvider

    property with the following statement:


    private TripDataProvider tripDataProvider = new TripDataProvider();

  12. Press F11 to build the project.
  13. Close and reopen the project.

    You must close and reopen the project to make the new data provider appear in the list of available data providers.

Creating the FilmHelper.java Helper Class

You will now create a helper class in the

dvdrental

package that will be used to perform Hibernate queries on the database. You will use the Hibernate Query Language (HQL) editor to construct and test the queries for retrieving data. After you test the queries you will create methods in the helper class that construct and run the queries. You will then invoke the methods in the helper class from a JSF managed bean.

Creating the Class

In this section you use the New File wizard to create the helper class

FilmHelper.java

in the

dvdrental

package. You will create a Hibernate session by calling

getSessionFactory

in

HibernateUtil.java

and create some helper methods to create queries to retrieve data from the database. You will invoke the helper methods from the JSP pages.

  1. Right-click the


    dvdrental

    source package node and select New > Java Class to open the New File wizard.

  2. Type FilmHelper for the class name.

  3. Confirm that dvdrental is selected as the Package. Click Finish.

  4. Adding the following code (in bold) to create a Hibernate session.


public class FilmHelper { *Session session = null; public FilmHelper() { this.session = HibernateUtil.getSessionFactory().getCurrentSession(); }* }

  1. Right-click in the editor and choose Fix Imports (Alt-Shift-I; ⌘-Shift-I on Mac) to add any required import statements (


    org.hibernate.Session

    ) and save your changes.

You will now modify

FilmHelper.java

to add methods that query the DB.

Enumerating Film Titles and Retrieving Actors Using an HQL Query

In this exercise you will create a Hibernate Query Language (HQL) query that queries the database to retrieve a list of film titles from the Film table. You will then add a method that queries both the Actor and Film_actor tables to fetch the actors involved in a particular film.

The Film table has 1000 records so the method to retrieve the list of films should be able to retrieve records based on the

filmId

primary key. You will use the HQL editor to construct and test the HQL query. After you have created the correct query you will add a method to the class that can generate the proper query.

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

  2. Right-click


    hibernate.cfg.xml

    in the Projects window and choose Run HQL Query to open the HQL query editor.

  3. Select hibernate.cfg from the drop down list in the toolbar.

  4. Test the connection by typing the following in the editor and clicking the Run HQL Query button ( images:./run_hql_query_16.png[title=”Run HQL Query button”] ) in the toolbar.


from Film

When you click Run HQL Query you can see the results of the query in the bottom window of the HQL query editor.

If you click the SQL button you can see the equivalent SQL query.


select film0_.film_id as col_0_0_ from sakila.film film0_

  1. Type the following query to retrieve the records in the Film table where the film id is between 100 and 200.


from Film as film where film.filmId between 100 and 200

The result window displays a list of records. Now that you have tested that the query returns the desired results, you can use the query in the helper class.

  1. Add the following method


    getFilmTitles

    to

    FilmHelper.java

    to retrieve the films where the film id is between a certain range specified by the variables

    startID

    and

    endID

    .


public List getFilmTitles(int startID, int endID) { List

filmList = null; try { org.hibernate.Transaction tx = session.beginTransaction(); Query q = session.createQuery ("from Film as film where film.filmId between '"+startID+"' and '"+endID+"'"); filmList = (List

) q.list(); } catch (Exception e) { e.printStackTrace(); } return filmList; }


  1. Add the following method


    getActorsByID

    that retrieves the actors in a particular film. The method constructs the query using

    filmId

    as the input variable.


public List getActorsByID(int filmId){ List

actorList = null; try { org.hibernate.Transaction tx = session.beginTransaction(); Query q = session.createQuery ("from Actor as actor where actor.actorId in (select filmActor.actor.actorId from FilmActor as filmActor where filmActor.film.filmId='" + filmId + "')"); actorList = (List

) q.list(); } catch (Exception e) { e.printStackTrace(); } return actorList; }


  1. Fix your imports and save your changes.

When you fix your imports you want to choose

java.util.List

and

org.hibernate.Query

.

Adding Additional Helper Methods

You will now add additional helper methods that create queries based on an input variable. You can check the queries in the HQL query editor.

  1. Add the following method to retrieve a list of categories according to


    filmId

    .


public Category getCategoryByID(int filmId){ List

categoryList = null; try { org.hibernate.Transaction tx = session.beginTransaction(); Query q = session.createQuery("from Category as category where category.categoryId in (select filmCat.category.categoryId from FilmCategory as filmCat where filmCat.film.filmId='" + filmId + "')"); categoryList = (List

) q.list(); } catch (Exception e) { e.printStackTrace(); } return categoryList.get(0); }


  1. Add the following method to retrieve a single film according to


    filmId

    .


public Film getFilmByID(int filmId){ Film film = null; try { org.hibernate.Transaction tx = session.beginTransaction(); Query q = session.createQuery("from Film as film where film.filmId=" + filmId); film = (Film) q.uniqueResult(); } catch (Exception e) { e.printStackTrace(); } return film; }

  1. Add the following method to retrieve the film language according to


    langId

    .


public String getLangByID(int langId){ Language language = null; try { org.hibernate.Transaction tx = session.beginTransaction(); Query q = session.createQuery("from Language as lang where lang.languageId=" + langId); language = (Language) q.uniqueResult(); } catch (Exception e) { e.printStackTrace(); } return language.getName(); }

  1. Save your changes.

#3. Hibernate Java Based Configuration with Maven + Eclipse + MySQL
#3. Hibernate Java Based Configuration with Maven + Eclipse + MySQL

Adding an Option Array Wrapper for the Person List

In this section, you add business logic to the session bean so that your project can access the Person data source using the Hibernate framework. First you add a session bean property to hold an array of

Option

objects for use by the DropDown List component. Then you add code to fill the array of

Option

objects with the results from a query on the Person database table.

  1. In the Outline window, right-click the SessionBean1 and choose Add > Property from the pop-up menu.

    If the Add menu item is disabled, close the pop-up window and try
    again.

  2. In the New Property Pattern dialog box, type

    personOptions

    in the Name text box, type

    Option[]

    in the Type text box, and click OK.

    Note that the newly added property might not appear in the Outline window.
    The property will appear after you open and save the SessionBean1 source file,
    which you do in the following steps.

  3. Double-click the SessionBean1 node to open the

    SessionBean1.java

    source file.

    Error annotations appear in the code as a result of unresolved classes. You can ignore these annotations for now. Later, you use the Fix Imports action to resolve these errors.

  4. Add the following code shown in bold to the end of the

    init

    method in the

    SessionBean1

    class.

    This code calls a query on the Person data source and stores the results in the

    personOptions

    array.

    Code Sample 1: Initializing the

    personOptions

    Array in the Session Bean’s

    init

    Method

    public void init() {
    // Perform initializations inherited from our superclass
    super.init();
    // Perform application initialization that must complete
    // *before* managed components are initialized
    // TODO – add your own initialization code here

    // Perform application initialization that must complete
    // *after* managed components are initialized
    // TODO – add your own initialization code here
    List personList = null;
    try{
    Session session =
    HibernateUtil.getSessionFactory().getCurrentSession();
    Transaction tx = session.beginTransaction();
    Query q = session.createQuery(“from Person”);
    personList = (List) q.list();
    } catch(Exception e) {
    e.printStackTrace();
    }
    personOptions = new Option[personList.size()];
    Iterator iter = personList.iterator();
    int i=0;
    while (iter.hasNext()) {
    Person person = (Person) iter.next();
    Option opt = new Option(“” + person.getPersonId(),
    person.getName());
    personOptions[i++] = opt;
    }
    }

  5. Right-click in the source and choose Fix Imports from the pop-up menu.

    The Fix Imports dialog appears.

  6. Select the following fully qualified names, and click OK.

    Class Name Fully Qualified Name

    Query

    org.hibernate.Query

    Session

    org.hibernate.Session

    List

    java.util.List

    Iterator

    java.util.Iterator

    Option

    com.sun.webui.jsf.model.Option

    for Java EE 5

    com.sun.rave.web.ui.model.Option

    for J2EE 1.4

    Transaction

    org.hibernate.Transaction
  7. Close and save the file.

Generating Hibernate Mapping Files and Java Classes

In this tutorial you use a POJO (plain old Java object) to represent the data in each of the tables in the database that you will use. The Java class specifies the fields for the columns in the tables and uses simple setters and getters to retrieve and write the data. To map the POJOs to the tables you can use a Hibernate mapping file or use annotations in the class.

You can use the Hibernate Mapping Files and POJOs from a Database wizard to create multiple POJOs and mapping files based on database tables. When you use the wizard you select all the tables for which you want POJOs and mapping files and the IDE then generates the files for you based on the database tables and 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).

Note. The IDE also has wizards to help you create individual POJOs and mapping files from scratch.

Creating the Hibernate Reverse Engineering File

If you want to use the Hibernate Mapping Files and POJOs from a Database wizard, you first need to create a

hibernate.reveng.xml

reverse engineering file. The Hibernate Mapping Files and POJOs from a Database wizard requires

hibernate.reveng.xml

and

hibernate.cfg.xml

.

The reverse engineering file enables you to have greater control over the database mapping strategy. The Hibernate Reverse Engineering Wizard creates a reverse engineering file with a default configuration that you can edit in the XML editor.

To create the Hibernate reverse engineering file, perform the following steps.

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

  2. Select Hibernate Reverse Engineering Wizard in the Hibernate category. Click Next.

  3. Specify


    hibernate.reveng

    as the File Name and

    src/java

    for the Folder. Click Next.

  4. Select


    hibernate.cfg.xml

    from the Configuration File drop down list, if not selected.

  5. Select the following tables from Available Tables and click Add to add the tables to Selected Tables.

    • actor

    • category

    • film

    • film_actor

    • film_category

    • language

Click Finish.

The wizard generates a

hibernate.reveng.xml

reverse engineering file and opens the file in the editor. You can close the reverse engineering file because you will not need to edit the file.

For more details about working with the

hibernate.reveng.xml

file, see Chapter 5. Controlling reverse engineering in the Hibernate Tools Reference Guide.

Creating the Hibernate Mapping Files and POJOs

You can use the Hibernate Mapping Files and POJOs from a Database wizard to generate files for you. The wizard can generate a POJO and a corresponding mapping file for each table that you select in the wizard. The mapping files are XML files that contain data about how the columns in the tables are mapped to the fields in the POJOs. You need to have the

hibernate.reveng.xml

and

hibernate.cfg.xml

files to use the wizard.

To create the POJOS and mapping files using a wizard, perform the following steps.

  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. Ensure that the


    hibernate.cfg.xml

    and

    hibernate.reveng.xml

    files are selected in the drop down lists.

  4. Select JDK 5 Language Features under the General Settings options.

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

  6. Select dvdrental for the Package name. Click Finish.

When you click Finish the IDE generates POJOs and Hibernate mapping files with the fields mapped to the columns specified in

hibernate.reveng.xml

. The IDE also adds mapping entries to

hibernate.cfg.xml

.



org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/sakila myusername mypassword true thread org.hibernate.hql.classic.ClassicQueryTranslatorFactory

Note. Confirm that the

mapping

elements are listed after the

property

elements in the

hibernate.cfg.xml

file.

You can expand the

dvdrental

package to see the files generated by the wizard.

You can use the Hibernate Mapping wizard if you want to create a Hibernate mapping file that maps a specific table to a specific class.

For more details about working with the

hibernate.reveng.xml

file, see Chapter 5. Basic O/R Mapping in the Hibernate Reference Documentation.

Login and Registration REST API using Spring Boot Mysql
Login and Registration REST API using Spring Boot Mysql

Creating the Web Pages

In this exercise you will create two web pages for displaying the data. You will modify the

index.xhtml

generated by the IDE to add a table that displays the films in the database. You will then create

browse.xhtml

to display a film’s details when you click the “View” link in the table. You will also create a JSF template page that is used by

index.xhtml

and

browse.xhtml

.

For more about using JSF 2.0 and Facelets templates, see Introduction to JavaServer Faces 2.0

Creating template.xhtml

You will first create the JSF Facelets template

template.xhtml

that is used in the composition of the

index.xhtml

and

browse.xhtml

pages.

  1. Right-click the DVDStore project node in the Projects window and choose New > Other.

  2. Select Facelets Template in the JavaServer Faces category. Click Next.

  3. Type template for the File Name and choose the first CSS layout style.

  4. Click Finish.

When you click Finish, the file

template.xhtml

opens in the editor. The template contains the following default code.



Top

Content


  1. Modify the

    element to change the default generated name to “body”.


Content

  1. Save your changes.

The content enclosed within the element in

index.xhtml

and

browse.xhtml

will be inserted into the location identified with


Content


in the template.

Modifying index.xhtml

When you created the web application, the IDE automatically generated the page

index.xhtml

. In this exercise you modify the page to display a list of film titles. The JSF page calls the methods in the JSF Managed Bean FilmController to retrieve the list of films and then displays a table with the film titles and descriptions.

  1. Expand the Web Pages folder in the Projects window and open


    index.xhtml

    in the editor.

The New Project wizard generated the following default

index.xhtml

page.




<br /> Facelet Title<br />


Hello from Facelets


  1. Modify the page to use the JSF

    andelements and add aelement.

When you start typing the tags, the IDE adds

xmlns:ui="http://java.sun.com/jsf/facelets"

tag library declaration.

The and elements are used in combination with the page template that you will create. The element references the location of the template that will be used by this page. The element references the position in the template that the enclosed code will occupy.

  1. Add the following navigation links that call the


    previous

    and

    next

    methods in the JSF managed bean.




* *


  1. Add the following


    dataTable

    element (in bold) to generate the table to display the retrieved items.



* *

  1. Save your changes.

The index page will now display a list of film titles in the database. Each row in the table includes a “View” link that invokes the

prepareView

method in the managed bean. The

prepareView

method returns “browse” and will open

browse.xhtml

.

Note. When you type the tag, the IDE will add

xmlns:f="http://java.sun.com/jsf/core

tag library declaration. Confirm that the tag library is declared in the file.

Creating browse.xhtml

You will now create the

browse.xhtml

page for displaying details of the selected film. You can use the Facelets Template Client wizard to create the page based on the JSF Facelets template

template.xhtml

that you created.

  1. Right-click DVDStore project node in the Projects window and choose New > Other.

  2. Select Facelets Template Client in the JavaServer Faces category. Click Next.

  1. Type browse for the File Name.

  2. Locate the Template for the page by clicking Browse to open the Browse Files dialog box.

  3. Expand the Web Pages folder and select


    template.xhtml

    . Click Select File.

  1. Select

    for the Generated Root Tag. Click Finish.

When you click Finish, the file

browse.xhtml

opens in the editor with the following code.




top


body


You can see that the new file specifies the

template.xhtml

file and that the tag has the property

name="body"

  1. Add the following code (in bold) between the

    tags to create the form and call the methods in the managed bean FilmController to retrieve the data and populate the form.




top


* *


You can see that

browse.xhtml

and

index.xhtml

will use the same page template.

  1. Save your changes.

History of Hibernate

Hibernate was started in 2001 by Gavin King with colleagues from Cirrus Technologies as an alternative to using EJB2-style entity beans. The original goal was to offer better persistence capabilities than those offered by EJB2.

In early 2003, the Hibernate development team began Hibernate2 releases. In 2005, Hibernate version 3.0 was released. In December 2018, Hibernate ORM 5.4.0 Final was released.

Using Hibernate in a Java Swing Application

This tutorial needs a review. You can edit it in GitHub following these contribution guidelines.
  • Creating the Database
  • Creating the Java Swing Application Project
  • Adding Hibernate Support to the Project
  • Generating Hibernate Mapping Files and Java Classes
  • Creating the Application GUI
  • Creating the Query in the HQL Query Editor
  • Adding the Query to the Form
  • Running the Project
  • Creating POJOs and Mapping Files Individually
  • See Also

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 (plain old Java objects) from a relational database.

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 GUI interface for searching and displaying the data.

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.

  • Hibernate documentation at hibernate.org.

  • Connecting to a MySQL Database tutorial.

To build this application using Maven, see Creating a Maven Swing Application Using Hibernate.

To follow this tutorial, you need the following software and resources.

Software or Resource Version Required

7.2, 7.3, 7.4, 8.0, Java

version 7 or 8

version 5.x

Sakila Database

plugin available from update center

You can download a zip archive of the finished project.

Login and Registration using JSP + Servlet + JDBC + MySQL [2022]-Complete Video
Login and Registration using JSP + Servlet + JDBC + MySQL [2022]-Complete Video

Generating Hibernate Mapping Files and Java Classes

In this tutorial you use a POJO (plain old Java object) to represent the data in each of the tables in the database that you will use. The Java class specifies the fields for the columns in the tables and uses simple setters and getters to retrieve and write the data. To map the POJOs to the tables you can use a Hibernate mapping file or use annotations in the class.

You can use the Hibernate Mapping Files and POJOs from a Database wizard to create multiple POJOs and mapping files based on database tables. When you use the wizard you select all the tables for which you want POJOs and mapping files and the IDE then generates the files for you based on the database tables and 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).

Note. The IDE also has wizards to help you create individual POJOs and mapping files from scratch.

Creating the Hibernate Reverse Engineering File

If you want to use the Hibernate Mapping Files and POJOs from a Database wizard, you first need to create a

hibernate.reveng.xml

reverse engineering file. The Hibernate Mapping Files and POJOs from a Database wizard requires

hibernate.reveng.xml

and

hibernate.cfg.xml

.

The reverse engineering file enables you to have greater control over the database mapping strategy. The Hibernate Reverse Engineering Wizard creates a reverse engineering file with a default configuration that you can edit in the XML editor.

To create the Hibernate reverse engineering file, perform the following steps.

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

  2. Select Hibernate Reverse Engineering Wizard in the Hibernate category. Click Next.

  3. Specify


    hibernate.reveng

    as the File Name and

    src/java

    for the Folder. Click Next.

  4. Select


    hibernate.cfg.xml

    from the Configuration File drop down list, if not selected.

  5. Select the following tables from Available Tables and click Add to add the tables to Selected Tables.

    • actor

    • category

    • film

    • film_actor

    • film_category

    • language

Click Finish.

The wizard generates a

hibernate.reveng.xml

reverse engineering file and opens the file in the editor. You can close the reverse engineering file because you will not need to edit the file.

For more details about working with the

hibernate.reveng.xml

file, see Chapter 5. Controlling reverse engineering in the Hibernate Tools Reference Guide.

Creating the Hibernate Mapping Files and POJOs

You can use the Hibernate Mapping Files and POJOs from a Database wizard to generate files for you. The wizard can generate a POJO and a corresponding mapping file for each table that you select in the wizard. The mapping files are XML files that contain data about how the columns in the tables are mapped to the fields in the POJOs. You need to have the

hibernate.reveng.xml

and

hibernate.cfg.xml

files to use the wizard.

To create the POJOS and mapping files using a wizard, perform the following steps.

  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. Ensure that the


    hibernate.cfg.xml

    and

    hibernate.reveng.xml

    files are selected in the drop down lists.

  4. Select JDK 5 Language Features under the General Settings options.

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

  6. Select dvdrental for the Package name. Click Finish.

When you click Finish the IDE generates POJOs and Hibernate mapping files with the fields mapped to the columns specified in

hibernate.reveng.xml

. The IDE also adds mapping entries to

hibernate.cfg.xml

.



org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/sakila myusername mypassword true thread org.hibernate.hql.classic.ClassicQueryTranslatorFactory

Note. Confirm that the

mapping

elements are listed after the

property

elements in the

hibernate.cfg.xml

file.

You can expand the

dvdrental

package to see the files generated by the wizard.

You can use the Hibernate Mapping wizard if you want to create a Hibernate mapping file that maps a specific table to a specific class.

For more details about working with the

hibernate.reveng.xml

file, see Chapter 5. Basic O/R Mapping in the Hibernate Reference Documentation.

How does Hibernate work?

Hibernate is an open source Object-Relational Persistence and Query service for any Java Application. Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieves the developer from most common data persistence related programming tasks.

Hibernate sits between traditional Java objects and database server to handle all the works in persisting those objects based on the appropriate O/R mechanisms and patterns.

Spring Boot Thymeleaf Web Application | Full Course ✅ | Student Management System Project
Spring Boot Thymeleaf Web Application | Full Course ✅ | Student Management System Project

Creating the FilmHelper.java Helper Class

You will now create a helper class in the

dvdrental

package that will be used to perform Hibernate queries on the database. You will use the Hibernate Query Language (HQL) editor to construct and test the queries for retrieving data. After you test the queries you will create methods in the helper class that construct and run the queries. You will then invoke the methods in the helper class from a JSF managed bean.

Creating the Class

In this section you use the New File wizard to create the helper class

FilmHelper.java

in the

dvdrental

package. You will create a Hibernate session by calling

getSessionFactory

in

HibernateUtil.java

and create some helper methods to create queries to retrieve data from the database. You will invoke the helper methods from the JSP pages.

  1. Right-click the


    dvdrental

    source package node and select New > Java Class to open the New File wizard.

  2. Type FilmHelper for the class name.

  3. Confirm that dvdrental is selected as the Package. Click Finish.

  4. Adding the following code (in bold) to create a Hibernate session.


public class FilmHelper { *Session session = null; public FilmHelper() { this.session = HibernateUtil.getSessionFactory().getCurrentSession(); }* }

  1. Right-click in the editor and choose Fix Imports (Alt-Shift-I; ⌘-Shift-I on Mac) to add any required import statements (


    org.hibernate.Session

    ) and save your changes.

You will now modify

FilmHelper.java

to add methods that query the DB.

Enumerating Film Titles and Retrieving Actors Using an HQL Query

In this exercise you will create a Hibernate Query Language (HQL) query that queries the database to retrieve a list of film titles from the Film table. You will then add a method that queries both the Actor and Film_actor tables to fetch the actors involved in a particular film.

The Film table has 1000 records so the method to retrieve the list of films should be able to retrieve records based on the

filmId

primary key. You will use the HQL editor to construct and test the HQL query. After you have created the correct query you will add a method to the class that can generate the proper query.

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

  2. Right-click


    hibernate.cfg.xml

    in the Projects window and choose Run HQL Query to open the HQL query editor.

  3. Select hibernate.cfg from the drop down list in the toolbar.

  4. Test the connection by typing the following in the editor and clicking the Run HQL Query button ( images:./run_hql_query_16.png[title=”Run HQL Query button”] ) in the toolbar.


from Film

When you click Run HQL Query you can see the results of the query in the bottom window of the HQL query editor.

If you click the SQL button you can see the equivalent SQL query.


select film0_.film_id as col_0_0_ from sakila.film film0_

  1. Type the following query to retrieve the records in the Film table where the film id is between 100 and 200.


from Film as film where film.filmId between 100 and 200

The result window displays a list of records. Now that you have tested that the query returns the desired results, you can use the query in the helper class.

  1. Add the following method


    getFilmTitles

    to

    FilmHelper.java

    to retrieve the films where the film id is between a certain range specified by the variables

    startID

    and

    endID

    .


public List getFilmTitles(int startID, int endID) { List

filmList = null; try { org.hibernate.Transaction tx = session.beginTransaction(); Query q = session.createQuery ("from Film as film where film.filmId between '"+startID+"' and '"+endID+"'"); filmList = (List

) q.list(); } catch (Exception e) { e.printStackTrace(); } return filmList; }


  1. Add the following method


    getActorsByID

    that retrieves the actors in a particular film. The method constructs the query using

    filmId

    as the input variable.


public List getActorsByID(int filmId){ List

actorList = null; try { org.hibernate.Transaction tx = session.beginTransaction(); Query q = session.createQuery ("from Actor as actor where actor.actorId in (select filmActor.actor.actorId from FilmActor as filmActor where filmActor.film.filmId='" + filmId + "')"); actorList = (List

) q.list(); } catch (Exception e) { e.printStackTrace(); } return actorList; }


  1. Fix your imports and save your changes.

When you fix your imports you want to choose

java.util.List

and

org.hibernate.Query

.

Adding Additional Helper Methods

You will now add additional helper methods that create queries based on an input variable. You can check the queries in the HQL query editor.

  1. Add the following method to retrieve a list of categories according to


    filmId

    .


public Category getCategoryByID(int filmId){ List

categoryList = null; try { org.hibernate.Transaction tx = session.beginTransaction(); Query q = session.createQuery("from Category as category where category.categoryId in (select filmCat.category.categoryId from FilmCategory as filmCat where filmCat.film.filmId='" + filmId + "')"); categoryList = (List

) q.list(); } catch (Exception e) { e.printStackTrace(); } return categoryList.get(0); }


  1. Add the following method to retrieve a single film according to


    filmId

    .


public Film getFilmByID(int filmId){ Film film = null; try { org.hibernate.Transaction tx = session.beginTransaction(); Query q = session.createQuery("from Film as film where film.filmId=" + filmId); film = (Film) q.uniqueResult(); } catch (Exception e) { e.printStackTrace(); } return film; }

  1. Add the following method to retrieve the film language according to


    langId

    .


public String getLangByID(int langId){ Language language = null; try { org.hibernate.Transaction tx = session.beginTransaction(); Query q = session.createQuery("from Language as lang where lang.languageId=" + langId); language = (Language) q.uniqueResult(); } catch (Exception e) { e.printStackTrace(); } return language.getName(); }

  1. Save your changes.

Benefits of Hibernate

Any changes made are encapsulated in the data source itself, so that when those sources or their application programming interfaces (APIs) change, the applications that use ORM don’t have to make changes or even be aware of that information. Similarly, programmers can have a consistent view of objects over time, although the sources that deliver them, the sinks that receive them and the applications that access them may change.

Hibernate is freely available to download and is licensed under the open source GNU Lesser General Public License (LGPL).

Hibernate Tutorial For Beginners | Java Hibernate in 100 minutes | Hibernate Project | Simplilearn
Hibernate Tutorial For Beginners | Java Hibernate in 100 minutes | Hibernate Project | Simplilearn

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.

When you click OK a Sakila node appears 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.

Creating the JSF Managed Bean

In this exercise you will create a JSF managed bean. The methods in the managed bean are used for displaying data in the JSF pages and for accessing methods in the helper class to retrieve records. The JSF 2.0 specification enables you to use annotations in a bean class to identify the class as a JSF managed bean, to specify the scope and to specify a name for the bean.

To create the managed bean, perform the following steps.

  1. Right-click the


    dvdrental

    source package node and choose New > Other.

  2. Select JSF Managed Bean from the JavaServer Faces category. Click Next.

  3. Type FilmController for the Class Name.

You will use the Managed Bean name

filmController

as the value for the

inputText

and

commandButton

in the JSF page

index.xhtml

when calling methods in the bean.

  1. Select dvdrental for the Package.

  2. Type filmController for the Name that will be used for the managed bean.

  3. Set Scope to Session. Click Finish.

When you click Finish, the IDE creates the bean class and opens the class in the editor. The IDE added the

@ManagedBean

and

@SessionScoped

annotations.


@ManagedBean @SessionScoped public class FilmController { /** Creates a new instance of FilmController */ public FilmController() { } }

Note. Note that the name of the managed bean is not explicitly specified. By default, the name of the bean is the same as the class name and begins with a lower-case letter. If you want the name of the bean to be different from the class name, you can explicitly specify the name as a parameter of the

@ManagedBean

annotations (for example,

@ManagedBean(name="myBeanName")

.

  1. Add the following fields (in bold) to the class.


@ManagedBean @SessionScoped public class FilmController { *int startId; int endId; DataModel filmTitles; FilmHelper helper; private int recordCount = 1000; private int pageSize = 10; private Film current; private int selectedItemIndex;* }

  1. Add the following code (in bold) to create the FilmController instance and retrieve the films.


/** Creates a new instance of FilmController */ public FilmController() { *helper = new FilmHelper(); startId = 1; endId = 10; } public FilmController(int startId, int endId) { helper = new FilmHelper(); this.startId = startId; this.endId = endId; } public Film getSelected() { if (current == null) { current = new Film(); selectedItemIndex = -1; } return current; } public DataModel getFilmTitles() { if (filmTitles == null) { filmTitles = new ListDataModel(helper.getFilmTitles(startId, endId)); } return filmTitles; } void recreateModel() { filmTitles = null; }*

  1. Add the following methods that are used to display the table and navigate the pages.* public boolean isHasNextPage() { if (endId + pageSize ⇐ recordCount) { return true; } return false; }

    public boolean isHasPreviousPage() { if (startId-pageSize > 0) { return true; } return false; }

    public String next() { startId = endId+1; endId = endId + pageSize; recreateModel(); return “index”; }

    public String previous() { startId = startId – pageSize; endId = endId – pageSize; recreateModel(); return “index”; }

    public int getPageSize() { return pageSize; }

    public String prepareView(){ current = (Film) getFilmTitles().getRowData(); return “browse”; } public String prepareList(){ recreateModel(); return “index”; } *

The methods that return “index” or “browse” will prompt the JSF navigation handler to try to open a page named

index.xhtml

or

browse.xhtml

. The JSF 2.0 specification enables the use of implicit navigation rules in applications that use Facelets technology. In this application, no navigation rules are configured in

faces-config.xml

. Instead, the navigation handler will try to locate a suitable page in the application.

  1. Add the following methods that access the helper class to retrieve additional film details.* public String getLanguage() { int langID = current.getLanguageByLanguageId().getLanguageId().intValue(); String language = helper.getLangByID(langID); return language; }

    public String getActors() { List actors = helper.getActorsByID(current.getFilmId()); StringBuffer totalCast = new StringBuffer(); for (int i = 0; i < actors.size(); i++) { Actor actor = (Actor) actors.get(i); totalCast.append(actor.getFirstName()); totalCast.append(” “); totalCast.append(actor.getLastName()); totalCast.append(” “); } return totalCast.toString(); }

    public String getCategory() { Category category = helper.getCategoryByID(current.getFilmId()); return category.getName(); }*

  1. Fix your imports (Ctrl-Shift-I) and save your changes.

You can use the code completion in the editor to help you type your code.

Java Database Connectivity | JDBC
Java Database Connectivity | JDBC

Hibernate and the NetBeans Visual Web Pack

Hibernate is an open source tool that provides object/relational persistence and query services. Hibernate sits between your application and database, and seamlessly loads and saves objects, assisting you with persistence content management.

This tutorial shows you how to build a Visual Web application that uses Hibernate libraries and plain old Java objects (POJOs). This tutorial is for developers who have a solid working knowledge of Hibernate. To learn more about Hibernate, see the Hibernate reference documentation.

In this tutorial, you wrap a Person POJO with an array of

model.Option

objects and bind a DropDown List component to the array. You then extend the

ObjectListDataProvider

class to build a

TripDataProvider

wrapper for the Trips POJO, and bind the Table component to an instance of the

TripDataProvider

class.

Note:
To learn more about the

model.Option

class, see Using List Components.

In this tutorial, you perform the following steps. These steps show the recommended method for building a Visual Web application that uses the Hibernate framework.

  1. Use the Library Manager tool to make the required Hibernate libraries available to the IDE. Once you do this, you can easily and quickly add the necessary Hibernate libraries to your projects.
  2. Create a Java Class Library project (POJO project) that segregates the Hibernate persistence code for the database tables into a reusable Hibernate front end.
  3. Add the database driver and the required Hibernate libraries to the POJO project.
  4. Develop a Visual Web Application project that references the POJO project and the Hibernate libraries.
  5. Use wrapper classes to connect the components to the Hibernate persistence classes.

Adding the Object List Data Provider Wrapper for the Trips List

In this section you extend the

ObjectListDataProvider

class to build a

TripDataProvider

wrapper for the results from a trips query.

  1. In the Projects window, right-click HibernateTutorialApp >
    Source Packages > hibernatetutorialapp and choose New > Java Class.
  2. Name the class

    TripDataProvider

    and click Finish.

    A TripDataProvider.java node appears under the hibernatetutorialapp package node and the IDE displays the source code for the

    TripDataProvider

    class.

  3. Replace the class definition with the following code.

    Code Sample 2:

    TripDataProvider

    Class

    public class TripDataProvider extends ObjectListDataProvider{
    private ArrayList tripsList = new ArrayList();
    // Note: to eliminate warnings when using Java SE 1.5, use instead
    // private ArrayList
    tripsList = new ArrayList
    ();
    /** Creates a new instance of tripDataProvider */
    public TripDataProvider() {
    // Put in dummy data for design time
    tripsList.add(new Trip());
    // Wrap the list
    setList(tripsList);
    }
    public void refreshTripsList(Integer personId){
    tripsList.clear();
    try{
    Session session =
    HibernateUtil.getSessionFactory().getCurrentSession();
    Transaction tx = session.beginTransaction();
    Person person =
    (Person)
    session.load(Person.class, personId);
    Set personTrips = (PersistentSet)person.getTrips();
    tripsList.addAll(personTrips);
    tx.commit();
    } catch(Exception e){
    e.printStackTrace();
    }
    }
    }

  4. Right-click in the source and choose Fix Imports from the pop-up menu.
  5. Select the following fully qualified names, and click OK.

    Class Name Fully Qualified Name

    Session

    org.hibernate.Session

    Transaction

    org.hibernate.Transaction

    Set

    java.util.Set
  6. Close and save the file.
  7. In the Outline window, right-click the SessionBean1 node and choose Add > Property from the pop-up menu.
  8. In the New Property Pattern dialog box, type

    tripDataProvider

    in the Name text box, type

    TripDataProvider

    in the Type text box, and click OK.
  9. Double-click the SessionBean1 node to open the

    SessionBean1.java

    source file.
  10. In the Navigation window, double-click the tripDataProvider node.

    The IDE scrolls the source code to the declaration for the tripDataProvider property.

  11. Replace the declaration for the

    tripDataProvider

    property with the following statement:


    private TripDataProvider tripDataProvider = new TripDataProvider();

  12. Press F11 to build the project.
  13. Close and reopen the project.

    You must close and reopen the project to make the new data provider appear in the list of available data providers.

Hibernate Create, Read, Update and Delete (CRUD) Operations Example
Hibernate Create, Read, Update and Delete (CRUD) Operations Example

Creating the Java Swing Application Project

In this exercise you create a simple Java Swing application project called DVDStoreAdmin.

  1. Choose File > New Project (Ctrl-Shift-N). Select Java Application from the Java category and click Next.

  2. Type DVDStoreAdmin for the project name and set the project location.

  3. Deselect the Use Dedicated Folder option, if selected. For this tutorial there is little reason to copy project libraries to a dedicated folder because you will not need to share libraries with other users.

    1. Deselect Create Main Class. Click Finish.

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.

Creating a Hibernate Class Library

You begin this tutorial by downloading the Hibernate library files and using the Library Manager tool to make the required Hibernate libraries available to the IDE.

  1. Download

    hibernate-3.2.2.ga.zip

    from hibernate and extract the files. Note: The examples in this tutorial use Hibernate 3.2.2 and the associated JAR files that are provided with that version. If you use a different version, the JAR library names and version numbers might vary. In addition, the list of JAR libraries to add might differ.
  2. In the IDE, choose Tools > Library Manager from the main menu.
  3. Click New Library, type

    Hibernate322

    in the Library Name field, and click OK.
  4. Click Add JAR/Folder and navigate to the directory into which you extracted the Hibernate files.
  5. Select

    hibernate3.jar

    and press Enter.
  6. Click Add JAR/Folder again, and navigate into the

    lib

    subdirectory.
  7. Use Ctrl-Click to select the following 10 JAR files and press Enter. If you are using a different version than 3.2.2, consult Hibernate’s web site to determine which JAR files to select.


    • ant-1.6.5.jar

    • antlr-2.7.6.jar

    • asm-attrs.jar

    • asm.jar

    • cglib-2.1.3.jar

    • commons-logging-1.0.4.jar

    • commons-collections-2.1.1.jar

    • dom4j-1.6.1.jar

    • ehcache-1.2.3.jar

    • jdbc2_0-stdext.jar

    The following figure shows the Hibernate library in the Library Manager window.

    Figure 1: Library Manager Window Showing the Hibernate Library
  8. If you are deploying your application to the Tomcat server, you must
    also add

    jta.jar

    from the Hibernate

    lib

    directory.
  9. To make the Hibernate Javadoc available to the Java Editor, select the Javadoc tab, click Add Zip/Folder, navigate to the directory into which you extracted the Hibernate files, select the

    doc/api

    subdirectory, and press Enter.
  10. (Optional) If you want to step into Hibernate classes during a debugging session, click the Sources tab, click Add JAR/Folder, navigate to the directory into which you extracted the Hibernate files, select the

    src

    subdirectory, and press Enter.
  11. Click OK to close the Library Manager.
Simple CRUD Part 1: Hibernate Setup in NetBeans 8.2 - Create
Simple CRUD Part 1: Hibernate Setup in NetBeans 8.2 – Create

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 Library dialog box.

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.

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 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 open the New File wizard.

  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


    src

    directory). Click Next.

  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 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 Hibernate JAR files and the MySQL connector JAR.

Note. NetBeans IDE 8.0 bundles the Hibernate 4 libraries. Older versions of the IDE bundled Hibernate 3.

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.

  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.

  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 as the Property Value.

This is the translator factory class that is used in Hibernate 4 that is bundled with the IDE.

Click OK.

If you are using NetBeans IDE 7.4 or earlier you should select org.hibernate.hql.classic.ClassicQueryTranslatorFactory as the Property Value in the dialog box. NetBeans IDE 7.4 and earlier bundled Hibernate 3.

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



org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/sakila root ###### true org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory

  1. Save your changes to the file.

After you create the form and set it as the main class you will be able to see the SQL query printed in the IDE’s Output window when you run the project.

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

.

  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.

  1. 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 need to edit the file.

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.

  2. Expand the

    source package node in the Projects window.

  3. Right-click


    hibernate.cfg.xml

    and choose Run HQL Query to open the HQL Editor.

  4. Test the connection by typing


    from Actor

    in the HQL Query Editor. Click the Run HQL Query button () in the toolbar.

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

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

JSP Servlet Hibernate Database Web Application (Registration Module) | Java Guides
JSP Servlet Hibernate Database Web Application (Registration Module) | Java Guides

Creating the Web Pages

In this exercise you will create two web pages for displaying the data. You will modify the

index.xhtml

generated by the IDE to add a table that displays the films in the database. You will then create

browse.xhtml

to display a film’s details when you click the “View” link in the table. You will also create a JSF template page that is used by

index.xhtml

and

browse.xhtml

.

For more about using JSF 2.0 and Facelets templates, see Introduction to JavaServer Faces 2.0

Creating template.xhtml

You will first create the JSF Facelets template

template.xhtml

that is used in the composition of the

index.xhtml

and

browse.xhtml

pages.

  1. Right-click the DVDStore project node in the Projects window and choose New > Other.

  2. Select Facelets Template in the JavaServer Faces category. Click Next.

  3. Type template for the File Name and choose the first CSS layout style.

  4. Click Finish.

When you click Finish, the file

template.xhtml

opens in the editor. The template contains the following default code.



Top

Content


  1. Modify the

    element to change the default generated name to “body”.


Content

  1. Save your changes.

The content enclosed within the element in

index.xhtml

and

browse.xhtml

will be inserted into the location identified with


Content


in the template.

Modifying index.xhtml

When you created the web application, the IDE automatically generated the page

index.xhtml

. In this exercise you modify the page to display a list of film titles. The JSF page calls the methods in the JSF Managed Bean FilmController to retrieve the list of films and then displays a table with the film titles and descriptions.

  1. Expand the Web Pages folder in the Projects window and open


    index.xhtml

    in the editor.

The New Project wizard generated the following default

index.xhtml

page.




<br /> Facelet Title<br />


Hello from Facelets


  1. Modify the page to use the JSF

    andelements and add aelement.

When you start typing the tags, the IDE adds

xmlns:ui="http://java.sun.com/jsf/facelets"

tag library declaration.

The and elements are used in combination with the page template that you will create. The element references the location of the template that will be used by this page. The element references the position in the template that the enclosed code will occupy.

  1. Add the following navigation links that call the


    previous

    and

    next

    methods in the JSF managed bean.




* *


  1. Add the following


    dataTable

    element (in bold) to generate the table to display the retrieved items.



* *

  1. Save your changes.

The index page will now display a list of film titles in the database. Each row in the table includes a “View” link that invokes the

prepareView

method in the managed bean. The

prepareView

method returns “browse” and will open

browse.xhtml

.

Note. When you type the tag, the IDE will add

xmlns:f="http://java.sun.com/jsf/core

tag library declaration. Confirm that the tag library is declared in the file.

Creating browse.xhtml

You will now create the

browse.xhtml

page for displaying details of the selected film. You can use the Facelets Template Client wizard to create the page based on the JSF Facelets template

template.xhtml

that you created.

  1. Right-click DVDStore project node in the Projects window and choose New > Other.

  2. Select Facelets Template Client in the JavaServer Faces category. Click Next.

  1. Type browse for the File Name.

  2. Locate the Template for the page by clicking Browse to open the Browse Files dialog box.

  3. Expand the Web Pages folder and select


    template.xhtml

    . Click Select File.

  1. Select

    for the Generated Root Tag. Click Finish.

When you click Finish, the file

browse.xhtml

opens in the editor with the following code.




top


body


You can see that the new file specifies the

template.xhtml

file and that the tag has the property

name="body"

  1. Add the following code (in bold) between the

    tags to create the form and call the methods in the managed bean FilmController to retrieve the data and populate the form.




top


* *


You can see that

browse.xhtml

and

index.xhtml

will use the same page template.

  1. Save your changes.

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.

  1. Open


    DVDStoreAdmin.java

    and click the Source tab.

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


public DVDStoreAdmin() { initComponents(); } *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(); session.beginTransaction(); Query q = session.createQuery(hql); List resultList = q.list(); displayResult(resultList); session.getTransaction().commit(); } catch (HibernateException he) { he.printStackTrace(); } }

The

executeHQLQuery()

method calls Hibernate to execute the selected query. This method makes use of the

HibernateUtil.java

utility class to obtain the Hibernate Session.

  1. Right-click in the editor and choose Fix Imports (Ctrl-Shift-I; ⌘-Shift-I on Mac) to generate import statements for the Hibernate libraries (


    org.hibernate.Query

    ,

    org.hibernate.Session

    ) and

    java.util.List

    . Save your changes.

  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("")) { runQueryBasedOnFirstName(); } else if(!lastNameTextField.getText().trim().equals("")) { runQueryBasedOnLastName(); }* }

  1. Add the following method to display the results in the JTable.


private void displayResult(List resultList) { Vector

tableHeaders = new Vector

(); Vector tableData = new Vector(); tableHeaders.add("ActorId"); tableHeaders.add("FirstName"); tableHeaders.add("LastName"); tableHeaders.add("LastUpdated"); for(Object o : resultList) { Actor actor = (Actor)o; Vector
oneRow = new Vector
(); oneRow.add(actor.getActorId()); oneRow.add(actor.getFirstName()); oneRow.add(actor.getLastName()); oneRow.add(actor.getLastUpdate()); tableData.add(oneRow); } resultTable.setModel(new DefaultTableModel(tableData, tableHeaders)); }



  1. Right-click in the editor and choose Fix Imports (Ctrl-Shift-I; ⌘-Shift-I on Mac) to generate an import statement for


    java.util.Vector

    and

    java.util.List

    . Save your changes.

After you save the form you can run the project.

ADV JAVA tutorials  by Mr. Nagoor Babu Sir
ADV JAVA tutorials by Mr. Nagoor Babu Sir

Creating the JSF Managed Bean

In this exercise you will create a JSF managed bean. The methods in the managed bean are used for displaying data in the JSF pages and for accessing methods in the helper class to retrieve records. The JSF 2.0 specification enables you to use annotations in a bean class to identify the class as a JSF managed bean, to specify the scope and to specify a name for the bean.

To create the managed bean, perform the following steps.

  1. Right-click the


    dvdrental

    source package node and choose New > Other.

  2. Select JSF Managed Bean from the JavaServer Faces category. Click Next.

  3. Type FilmController for the Class Name.

You will use the Managed Bean name

filmController

as the value for the

inputText

and

commandButton

in the JSF page

index.xhtml

when calling methods in the bean.

  1. Select dvdrental for the Package.

  2. Type filmController for the Name that will be used for the managed bean.

  3. Set Scope to Session. Click Finish.

When you click Finish, the IDE creates the bean class and opens the class in the editor. The IDE added the

@ManagedBean

and

@SessionScoped

annotations.


@ManagedBean @SessionScoped public class FilmController { /** Creates a new instance of FilmController */ public FilmController() { } }

Note. Note that the name of the managed bean is not explicitly specified. By default, the name of the bean is the same as the class name and begins with a lower-case letter. If you want the name of the bean to be different from the class name, you can explicitly specify the name as a parameter of the

@ManagedBean

annotations (for example,

@ManagedBean(name="myBeanName")

.

  1. Add the following fields (in bold) to the class.


@ManagedBean @SessionScoped public class FilmController { *int startId; int endId; DataModel filmTitles; FilmHelper helper; private int recordCount = 1000; private int pageSize = 10; private Film current; private int selectedItemIndex;* }

  1. Add the following code (in bold) to create the FilmController instance and retrieve the films.


/** Creates a new instance of FilmController */ public FilmController() { *helper = new FilmHelper(); startId = 1; endId = 10; } public FilmController(int startId, int endId) { helper = new FilmHelper(); this.startId = startId; this.endId = endId; } public Film getSelected() { if (current == null) { current = new Film(); selectedItemIndex = -1; } return current; } public DataModel getFilmTitles() { if (filmTitles == null) { filmTitles = new ListDataModel(helper.getFilmTitles(startId, endId)); } return filmTitles; } void recreateModel() { filmTitles = null; }*

  1. Add the following methods that are used to display the table and navigate the pages.* public boolean isHasNextPage() { if (endId + pageSize ⇐ recordCount) { return true; } return false; }

    public boolean isHasPreviousPage() { if (startId-pageSize > 0) { return true; } return false; }

    public String next() { startId = endId+1; endId = endId + pageSize; recreateModel(); return “index”; }

    public String previous() { startId = startId – pageSize; endId = endId – pageSize; recreateModel(); return “index”; }

    public int getPageSize() { return pageSize; }

    public String prepareView(){ current = (Film) getFilmTitles().getRowData(); return “browse”; } public String prepareList(){ recreateModel(); return “index”; } *

The methods that return “index” or “browse” will prompt the JSF navigation handler to try to open a page named

index.xhtml

or

browse.xhtml

. The JSF 2.0 specification enables the use of implicit navigation rules in applications that use Facelets technology. In this application, no navigation rules are configured in

faces-config.xml

. Instead, the navigation handler will try to locate a suitable page in the application.

  1. Add the following methods that access the helper class to retrieve additional film details.* public String getLanguage() { int langID = current.getLanguageByLanguageId().getLanguageId().intValue(); String language = helper.getLangByID(langID); return language; }

    public String getActors() { List actors = helper.getActorsByID(current.getFilmId()); StringBuffer totalCast = new StringBuffer(); for (int i = 0; i < actors.size(); i++) { Actor actor = (Actor) actors.get(i); totalCast.append(actor.getFirstName()); totalCast.append(” “); totalCast.append(actor.getLastName()); totalCast.append(” “); } return totalCast.toString(); }

    public String getCategory() { Category category = helper.getCategoryByID(current.getFilmId()); return category.getName(); }*

  1. Fix your imports (Ctrl-Shift-I) and save your changes.

You can use the code completion in the editor to help you type your code.

Creating a Web Project That Uses the Hibernate Framework

In this section, you create a Visual Web project and add the HibernateTravelPOJO Java class project to the web project. The following figure shows the web page that you build in this project.

Figure 3: HibernateTutorialApp Page1
  1. In the Runtime window, expand the Databases node.
  2. Right-click the jdbc node for the Travel database and choose Connect
    from the pop-up menu.
  3. In the Connect dialog box, enter

    travel

    for the Password,
    select Remember Password During This Session, and click OK.
  4. From the main menu, choose File > New Project.
  5. In the New Project Wizard, select Web from the Categories list and select
    Visual Web Application from the Projects list.
  6. Click Next.
  7. Name the project

    HibernateTutorialApp

    , select
    the Server and Java EE Version, and click Finish.

    Your project appears with the initial page (

    Page1

    ) open in the Visual Designer.

  8. In the Projects window, right-click HibernateTutorialApp > Libraries and choose Add Library.
  9. In the Add Library window, select Hibernate322 and click Add Library, as shown in the following figure.

    Figure 4: Adding the Hibernate Library
  10. Right-click HibernateTutorialApp > Libraries again,
    and choose Add Project.
  11. In the Add Project window, navigate to and choose HibernateTravelPOJO, and click Add Project JAR Files, as shown in the following figure.

    Figure 5: Adding the HibernateTravelPOJO Project
  12. Drag a Drop Down List component from the Palette and drop it in the top left corner of Page1 in the Visual Designer.
  13. Double-click the Drop Down List component that you
    just added to Page1.

    The IDE adds a method for processing a change in the drop-down list selection
    and displays the method in the source editor. The IDE also registers
    the method as a handler for the value change event.
    You add code to this method later.

  14. Click Design in the editing toolbar to switch back to the Visual
    Designer.
  15. Right-click the Drop Down List component and select Auto-Submit on Change from the pop-up menu.

    This action causes the browser to submit the page whenever the user chooses a new value from the drop-down list.

  16. Drag and drop a Message Group component to the right of the Drop Down List component.

    Message Group components help you to diagnose runtime problems.

  17. Drag and drop a Table component below the Drop Down List component.
#15 Registration Page Using Hibernate ,Servlet , JSP | Hibernate Tutorials
#15 Registration Page Using Hibernate ,Servlet , JSP | Hibernate Tutorials

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. Right-click in the editor and choose Insert Code (Alt-Insert; Ctrl-I on Mac) and select Getter and Setter in the popup menu to generate getters and setters for the fields.

  2. In the Generate Getters and Setters dialog box, select all the fields and click 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.

  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

Actor.java

.

  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 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 drop down list. Click Finish.

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:

  1. Map the fields in


    Actor.java

    to the columns in the ACTOR table by making the following changes (in bold) to

    Actor.hbm.xml

    .

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

By default, the generated
  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 customizing your application.

What is Hibernate?

Hibernate is an open source object relational mapping (ORM) tool that provides a framework to map object-oriented domain models to relational databases for web applications.

Object relational mapping is based on the containerization of objects and the abstraction that provides that capacity. Abstraction makes it possible to address, access and manipulate objects without having to consider how they are related to their data sources.

The Hibernate ORM framework guides mapping Java classes to database tables and Java data types to SQL data types and provides querying and retrieval.

Hibernate First Program using NetBeans IDE and Oracle
Hibernate First Program using NetBeans IDE and Oracle

Hibernate and the NetBeans Visual Web Pack

Hibernate is an open source tool that provides object/relational persistence and query services. Hibernate sits between your application and database, and seamlessly loads and saves objects, assisting you with persistence content management.

This tutorial shows you how to build a Visual Web application that uses Hibernate libraries and plain old Java objects (POJOs). This tutorial is for developers who have a solid working knowledge of Hibernate. To learn more about Hibernate, see the Hibernate reference documentation.

In this tutorial, you wrap a Person POJO with an array of

model.Option

objects and bind a DropDown List component to the array. You then extend the

ObjectListDataProvider

class to build a

TripDataProvider

wrapper for the Trips POJO, and bind the Table component to an instance of the

TripDataProvider

class.

Note:
To learn more about the

model.Option

class, see Using List Components.

In this tutorial, you perform the following steps. These steps show the recommended method for building a Visual Web application that uses the Hibernate framework.

  1. Use the Library Manager tool to make the required Hibernate libraries available to the IDE. Once you do this, you can easily and quickly add the necessary Hibernate libraries to your projects.
  2. Create a Java Class Library project (POJO project) that segregates the Hibernate persistence code for the database tables into a reusable Hibernate front end.
  3. Add the database driver and the required Hibernate libraries to the POJO project.
  4. Develop a Visual Web Application project that references the POJO project and the Hibernate libraries.
  5. Use wrapper classes to connect the components to the Hibernate persistence classes.

Running the Project

Now that the coding is finished, you can launch the application. Before you run the project, you need to 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.

  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.

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

  • 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:


      https://svn.netbeans.org/svn/samples~samples-source-code

      Click Next.

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

      2. Expand the root node and select samples/java/DVDStoreAdmin-Ant. 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.

Note. You need a Subversion client to checkout the sources. For more about installing Subversion, see the section on Setting up Subversion in the Guide to Subversion in NetBeans IDE.

Spring - Hibernate: step by step in netbeans
Spring – Hibernate: step by step in netbeans

Creating the Database

This tutorial uses a MySQL database called

sakila

, a free sample MySQL database that is available from the MySQL site. The sakila database is not included when you install the IDE so you need to first create the database to follow this tutorial.

To create the sakila database you can download and install the Sakila Sample Database plugin using the Plugins manager. After you install the plugin 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 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.

When you click OK a Sakila node appears 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.

Creating the Web Application Project

In this exercise you will create a web application project and add the Hibernate libraries to the project. When you create the project, you will select Hibernate in the Frameworks panel of the New Project wizard and specify the database.

  1. Choose File > New Project (Ctrl-Shift-N; ⌘-Shift-N on Mac) from the main menu. Select Web Application from the Java Web category and click Next.

  2. Type DVDStore for the project name and set the project location.

  3. Deselect the Use Dedicated Folder option, if selected. Click Next.

For this tutorial there is little reason to copy project libraries to a dedicated folder because you will not need to share libraries with other users.

  1. Set the server to the GlassFish Server and set the Java EE Version to Java EE 6 Web or Java EE 7 Web. Click Next.

  2. Select the JavaServer Faces checkbox and use the default JSF 2.x libraries.

  3. Select the Hibernate checkbox in the list of frameworks.

  4. Select the sakila database from the Database Connection drop down list. Click Finish.

Note: If the sakila database is not available as an option in the Frameworks panel in the wizard, check to see if the connection is listed under the Databases node in the Services window. If the connection is not there, you need to create the database connection.

When you click Finish, the IDE creates the web application project and opens the

hibernate.cfg.xml

file and

index.xhtml

in the editor.

If you expand the Libraries node in the Projects window, you can see that the IDE added the Hibernate libraries to the project.

JAVA Hibernate CRUD Create Read Update Delete Project
JAVA Hibernate CRUD Create Read Update Delete Project

Binding the Components to the Data Wrappers

In this section, you bind the components to the data wrappers and add logic to synchronize the data in the Table component with the selected person.

  1. Open Page1 in the Visual Designer.
  2. Right-click the Drop Down List component and choose Bind to Data from the pop-up menu.
  3. In the Bind to an Object tab, select SessionBean1 > personOptions and click OK.
  4. Right-click the Table component and choose Table Layout from the pop-up menu.
  5. Choose tripDataProvider from the Get Data From drop-down list.

    Note: If tripDataProvider is not available from the drop-down list, build, close, and reopen the project, and try again.

  6. Select personId in the Selected list and click the left-arrow button to move the field from the Selected list to the Available list.
  7. Use the Up and Down buttons to arrange the remaining fields in the following order, as shown in Figure 6, and click OK.

    • tripId
    • depDate
    • depCity
    • destCity
    • tripTypeId
    Figure 6: Binding the Table Component to the

    tripDataProvider

    Wrapper
  8. In the Editing toolbar, click Java to open

    Page1.java

    in the Java Editor.
  9. In the

    prerender

    method, add the following code shown in bold.

    Code Sample 3:

    prerender

    Method

    public void prerender() {
    try {
    if (dropDown1.getSelected() == null ) {
    Option firstPerson = getSessionBean1().getPersonOptions()[0];
    getSessionBean1().getTripDataProvider().refreshTripsList(
    new Integer((String)firstPerson.getValue()));
    }
    } catch (Exception ex) {
    log(“Error Description”, ex);
    error(ex.getMessage());
    }
    }

    This code causes the page to display the information for the first person in the drop-down list when the user first visits the page.

  10. Right-click in the source and choose Fix Imports from the pop-up menu.

    The Fix Imports dialog appears.

  11. In the Fully Qualified Name drop-down list, select

    com.sun.webui.jsf.model.Option

    for Java EE 5
    projects and

    com.sun.rave.web.ui.model.Option

    for J2EE 1.4 projects.
  12. Click OK.
  13. Add the following code shown in bold to the

    dropDown1_processValueChange

    method.

    Code Sample 4:

    dropDown1_processValueChange

    Method

    public void dropDown1_processValueChange(ValueChangeEvent event) {
    try {
    Integer personId =
    new Integer((String)dropDown1.getSelected());
    getSessionBean1().getTripDataProvider().refreshTripsList(
    personId);
    } catch(Exception ex) {
    log(“Error getting Person List : “, ex);
    error(“Error getting Person List: ” + ex.getMessage());
    }
    }

    This code causes the page to display the trips for the selected person.

  14. In the main toolbar, click Run Main Project to run the project.
  15. Select a person’s name from the drop-down list to display that person’s trips.

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

configure()

and 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 dvdrental for the package. Click Finish.

When you click Finish,

HibernateUtil.java

opens in the editor. You can close the file because you do not need to edit the file.

How to Create Java Web Project in NetBeans
How to Create Java Web Project in NetBeans

Adding an Option Array Wrapper for the Person List

In this section, you add business logic to the session bean so that your project can access the Person data source using the Hibernate framework. First you add a session bean property to hold an array of

Option

objects for use by the DropDown List component. Then you add code to fill the array of

Option

objects with the results from a query on the Person database table.

  1. In the Outline window, right-click the SessionBean1 and choose Add > Property from the pop-up menu.

    If the Add menu item is disabled, close the pop-up window and try
    again.

  2. In the New Property Pattern dialog box, type

    personOptions

    in the Name text box, type

    Option[]

    in the Type text box, and click OK.

    Note that the newly added property might not appear in the Outline window.
    The property will appear after you open and save the SessionBean1 source file,
    which you do in the following steps.

  3. Double-click the SessionBean1 node to open the

    SessionBean1.java

    source file.

    Error annotations appear in the code as a result of unresolved classes. You can ignore these annotations for now. Later, you use the Fix Imports action to resolve these errors.

  4. Add the following code shown in bold to the end of the

    init

    method in the

    SessionBean1

    class.

    This code calls a query on the Person data source and stores the results in the

    personOptions

    array.

    Code Sample 1: Initializing the

    personOptions

    Array in the Session Bean’s

    init

    Method

    public void init() {
    // Perform initializations inherited from our superclass
    super.init();
    // Perform application initialization that must complete
    // *before* managed components are initialized
    // TODO – add your own initialization code here

    // Perform application initialization that must complete
    // *after* managed components are initialized
    // TODO – add your own initialization code here
    List personList = null;
    try{
    Session session =
    HibernateUtil.getSessionFactory().getCurrentSession();
    Transaction tx = session.beginTransaction();
    Query q = session.createQuery(“from Person”);
    personList = (List) q.list();
    } catch(Exception e) {
    e.printStackTrace();
    }
    personOptions = new Option[personList.size()];
    Iterator iter = personList.iterator();
    int i=0;
    while (iter.hasNext()) {
    Person person = (Person) iter.next();
    Option opt = new Option(“” + person.getPersonId(),
    person.getName());
    personOptions[i++] = opt;
    }
    }

  5. Right-click in the source and choose Fix Imports from the pop-up menu.

    The Fix Imports dialog appears.

  6. Select the following fully qualified names, and click OK.

    Class Name Fully Qualified Name

    Query

    org.hibernate.Query

    Session

    org.hibernate.Session

    List

    java.util.List

    Iterator

    java.util.Iterator

    Option

    com.sun.webui.jsf.model.Option

    for Java EE 5

    com.sun.rave.web.ui.model.Option

    for J2EE 1.4

    Transaction

    org.hibernate.Transaction
  7. Close and save the file.

Creating the Web Application Project

In this exercise you will create a web application project and add the Hibernate libraries to the project. When you create the project, you will select Hibernate in the Frameworks panel of the New Project wizard and specify the database.

  1. Choose File > New Project (Ctrl-Shift-N; ⌘-Shift-N on Mac) from the main menu. Select Web Application from the Java Web category and click Next.

  2. Type DVDStore for the project name and set the project location.

  3. Deselect the Use Dedicated Folder option, if selected. Click Next.

For this tutorial there is little reason to copy project libraries to a dedicated folder because you will not need to share libraries with other users.

  1. Set the server to the GlassFish Server and set the Java EE Version to Java EE 6 Web or Java EE 7 Web. Click Next.

  2. Select the JavaServer Faces checkbox and use the default JSF 2.x libraries.

  3. Select the Hibernate checkbox in the list of frameworks.

  4. Select the sakila database from the Database Connection drop down list. Click Finish.

Note: If the sakila database is not available as an option in the Frameworks panel in the wizard, check to see if the connection is listed under the Databases node in the Services window. If the connection is not there, you need to create the database connection.

When you click Finish, the IDE creates the web application project and opens the

hibernate.cfg.xml

file and

index.xhtml

in the editor.

If you expand the Libraries node in the Projects window, you can see that the IDE added the Hibernate libraries to the project.

CRUD Enterprise Application in NetBeans using EJB, JPA and JSF
CRUD Enterprise Application in NetBeans using EJB, JPA and JSF

Modifying the Hibernate Configuration File

When you create a new project that uses the Hibernate framework, the IDE automatically creates the

hibernate.cfg.xml

configuration file at the root of the context classpath of the application (in the Files window,

src/java

). The file is located in the under the Source Packages node in the Projects window. The configuration file contains information about the database connection, resource mappings, and other connection properties. You can edit the file using the multi-view editor, or edit the XML directly in the XML editor.

In this exercise you will edit the default properties specified in

hibernate.cfg.xml

to enable debug logging for SQL statements and to enable Hibernate’s session context management.

  1. Open


    hibernate.cfg.xml

    in the Design tab. You can open the file by expanding thenode under Source Packages in the Projects window and double-clicking

    hibernate.cfg.xml

    .

  2. In the multi-view XML editor, 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

    . This enables the debug logging of the SQL statements.

  1. Expand the Miscellaneous Properties node and click Add.

  2. In the dialog box, select the


    properties hibernate.current_session_context_class

    and set the value to

    thread

    to enable Hibernate’s automatic session context management.

  1. Click Add again under the Miscellaneous Properties node and select


    hibernate.query.factory_class

    in the Property Name dropdown list.

  2. Select org.hibernate.hql.classic.ClassicQueryTranslatorFactory as the Property Value. Click OK.

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 (the three new properties are bold):



org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/sakila root ###### * true thread org.hibernate.hql.classic.ClassicQueryTranslatorFactory *


  1. Save your changes to the file.

You can close the file because you do not need to edit the file again.

Running the Project

The basics of the application are now complete. You can now run the application to check if everything is working correctly.

  1. Click Run Main Project in the main toolbar or right-click the DVDStore application node in the Projects window and choose Run.

The IDE saves all changed files, builds the application, and deploys the application to the server. The IDE opens a browser window to the URL

http://localhost:8080/DVDStore/

that displays the list of films.

  1. In your browser, click “View” to load


    browse.xhtml

    to view the film details.

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:


      https://svn.netbeans.org/svn/samples~samples-source-code

      Click Next.

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

      2. Expand the root node and select samples/javaee/DVDStoreEE6. Click OK.

      3. Specify the Local Folder for the sources.

      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.

Notes. For more about installing Subversion, see the section on Setting up Subversion in the Guide to Subversion in NetBeans IDE.

Troubleshooting

Most of the problems that occur with the tutorial application are due to communication difficulties between the GlassFish Server Open Source Edition and the MySQL database server. If your application does not display correctly, or if you are receiving a server error, you might want to look at the Troubleshooting section of the Creating a Simple Web Application Using a MySQL Database tutorial or the Connecting to a MySQL Database tutorial.

If you download and run the solution project you might see the following error in the Output window if it is the first time that you have deployed an application that uses the MySQL database.


SEVERE: JDBC Driver class not found: com.mysql.jdbc.Driver java.lang.ClassNotFoundException: com.mysql.jdbc.Driver at org.glassfish.web.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1509) [...] at java.lang.Thread.run(Thread.java:680) SEVERE: Initial SessionFactory creation failed.org.hibernate.HibernateException: JDBC Driver class not found: com.mysql.jdbc.Driver INFO: cleaning up connection pool: null INFO: Domain Pinged: stable.glassfish.org

In your browser window you might see a

java.lang.ExceptionInInitializerError

and the following stack trace.


java.lang.ExceptionInInitializerError at dvdrental.HibernateUtil.

(HibernateUtil.java:28) ... Caused by: org.hibernate.HibernateException: JDBC Driver class not found: com.mysql.jdbc.Driver ... Caused by: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver ...

The output message states that the JDBC driver for the MySQL database was not found. The most probable reason is that you need to add the MySQL JDBC driver file to your GlassFish server installation. To confirm that the driver is missing, navigate to the

GLASSFISH-INSTALL/glassfish/domains/domain1/lib

directory on your local system (where GLASSFISH-INSTALL is your GlassFish installation directory). If the

domain1/lib

directory does not contain the JDBC driver file (for example,

mysql-connector-java-5.1.13-bin.jar

) you need to copy the JDBC driver to the directory. The MySQL JDBC driver is not added to your GlassFish installation when you install the server.

You can add a copy of the MySQL JDBC driver to your GlassFish installation by performing the following steps.

  1. Download the MySQL Connector/J JDBC driver.

  2. Extract the driver and copy the driver file (for example,


    mysql-connector-java-5.1.13-bin.jar

    ) to the

    domain1/lib

    directory of your GlassFish installation.

Alternatively, when you use the IDE to create an application that uses the MySQL database, the IDE can automatically copy the bundled MySQL JDBC driver to the GlassFish server when you deploy the project, if required. To confirm that the IDE will copy the necessary JDBC drivers, choose Tools > Servers from the main menu to open the Servers manager and confirm that the Enable JDBC Driver Deployment option is selected for your GlassFish server.

After you create and deploy a web application that uses the MySQL database, if you navigate to the

domain1/lib

directory of your local GlassFish installation you will see that directory contains the JDBC driver file.

Using Hibernate in a Java Swing Application

This tutorial needs a review. You can edit it in GitHub following these contribution guidelines.
  • Creating the Database
  • Creating the Java Swing Application Project
  • Adding Hibernate Support to the Project
  • Generating Hibernate Mapping Files and Java Classes
  • Creating the Application GUI
  • Creating the Query in the HQL Query Editor
  • Adding the Query to the Form
  • Running the Project
  • Creating POJOs and Mapping Files Individually
  • See Also

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 (plain old Java objects) from a relational database.

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 GUI interface for searching and displaying the data.

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.

  • Hibernate documentation at hibernate.org.

  • Connecting to a MySQL Database tutorial.

To build this application using Maven, see Creating a Maven Swing Application Using Hibernate.

To follow this tutorial, you need the following software and resources.

Software or Resource Version Required

7.2, 7.3, 7.4, 8.0, Java

version 7 or 8

version 5.x

Sakila Database

plugin available from update center

You can download a zip archive of the finished project.

Hibernate CRUD example with JSP Serlvets
Hibernate CRUD example with JSP Serlvets

See Also

For additional information on creating Swing GUI applications, see the following tutorials.

Messages:
File: org/apache/catalina/servlets/DefaultServlet.java
Line number: 868

org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:614) org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:246) org.apache.struts2.views.tiles.TilesResult.doExecute(TilesResult.java:105) org.apache.struts2.dispatcher.StrutsResultSupport.execute(StrutsResultSupport.java:186) com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:362) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:266) com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:165) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:252) org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:179) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:130) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:165) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:179) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52) org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:488) org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77) org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91) org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190) org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542) org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357) org.apache.coyote.ajp.AjpProcessor.service(AjpProcessor.java:433) org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893) org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1723) org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) java.lang.Thread.run(Thread.java:748)

org.apache.tiles.servlet.context.ServletTilesRequestContext.wrapServletException(ServletTilesRequestContext.java:298) org.apache.tiles.servlet.context.ServletTilesRequestContext.forward(ServletTilesRequestContext.java:200) org.apache.tiles.servlet.context.ServletTilesRequestContext.dispatch(ServletTilesRequestContext.java:179) org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:606) org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:246) org.apache.struts2.views.tiles.TilesResult.doExecute(TilesResult.java:105) org.apache.struts2.dispatcher.StrutsResultSupport.execute(StrutsResultSupport.java:186) com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:362) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:266) com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:165) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:252) org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:179) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:130) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:165) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:179) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52) org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:488) org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77) org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91) org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190) org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542) org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357) org.apache.coyote.ajp.AjpProcessor.service(AjpProcessor.java:433) org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893) org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1723) org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) java.lang.Thread.run(Thread.java:748)

org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:669) org.apache.jsp.mylayout_jsp._jspService(mylayout_jsp.java:638) org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) javax.servlet.http.HttpServlet.service(HttpServlet.java:764) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:466) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:379) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:327) javax.servlet.http.HttpServlet.service(HttpServlet.java:764) org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:228) org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190) org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:711) org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:459) org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:385) org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:313) org.apache.tiles.servlet.context.ServletTilesRequestContext.forward(ServletTilesRequestContext.java:198) org.apache.tiles.servlet.context.ServletTilesRequestContext.dispatch(ServletTilesRequestContext.java:179) org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:606) org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:246) org.apache.struts2.views.tiles.TilesResult.doExecute(TilesResult.java:105) org.apache.struts2.dispatcher.StrutsResultSupport.execute(StrutsResultSupport.java:186) com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:362) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:266) com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:165) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:252) org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:179) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:130) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:165) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:179) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52) org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:488) org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77) org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91) org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190) org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542) org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357) org.apache.coyote.ajp.AjpProcessor.service(AjpProcessor.java:433) org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893) org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1723) org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) java.lang.Thread.run(Thread.java:748)

org.apache.catalina.servlets.DefaultServlet.serveResource(DefaultServlet.java:868) org.apache.catalina.servlets.DefaultServlet.doGet(DefaultServlet.java:519) javax.servlet.http.HttpServlet.service(HttpServlet.java:655) org.apache.catalina.servlets.DefaultServlet.service(DefaultServlet.java:499) javax.servlet.http.HttpServlet.service(HttpServlet.java:764) org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:228) org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:711) org.apache.catalina.core.ApplicationDispatcher.doInclude(ApplicationDispatcher.java:578) org.apache.catalina.core.ApplicationDispatcher.include(ApplicationDispatcher.java:517) org.apache.jasper.runtime.JspRuntimeLibrary.include(JspRuntimeLibrary.java:994) org.apache.jasper.runtime.PageContextImpl.include(PageContextImpl.java:500) org.apache.tiles.jsp.context.JspTilesRequestContext.include(JspTilesRequestContext.java:80) org.apache.tiles.jsp.context.JspTilesRequestContext.dispatch(JspTilesRequestContext.java:73) org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:283) org.apache.tiles.jsp.taglib.InsertAttributeTag.render(InsertAttributeTag.java:140) org.apache.tiles.jsp.taglib.InsertAttributeTag.render(InsertAttributeTag.java:117) org.apache.tiles.jsp.taglib.RenderTagSupport.execute(RenderTagSupport.java:154) org.apache.tiles.jsp.taglib.RoleSecurityTagSupport.doEndTag(RoleSecurityTagSupport.java:75) org.apache.tiles.jsp.taglib.ContainerTagSupport.doEndTag(ContainerTagSupport.java:80) org.apache.jsp.mylayout_jsp._jspx_meth_tiles_005finsertAttribute_005f2(mylayout_jsp.java:875) org.apache.jsp.mylayout_jsp._jspService(mylayout_jsp.java:239) org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) javax.servlet.http.HttpServlet.service(HttpServlet.java:764) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:466) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:379) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:327) javax.servlet.http.HttpServlet.service(HttpServlet.java:764) org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:228) org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190) org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:711) org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:459) org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:385) org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:313) org.apache.tiles.servlet.context.ServletTilesRequestContext.forward(ServletTilesRequestContext.java:198) org.apache.tiles.servlet.context.ServletTilesRequestContext.dispatch(ServletTilesRequestContext.java:179) org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:606) org.apache.tiles.impl.BasicTilesContainer.render(BasicTilesContainer.java:246) org.apache.struts2.views.tiles.TilesResult.doExecute(TilesResult.java:105) org.apache.struts2.dispatcher.StrutsResultSupport.execute(StrutsResultSupport.java:186) com.opensymphony.xwork2.DefaultActionInvocation.executeResult(DefaultActionInvocation.java:362) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:266) com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:165) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:252) org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:68) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ConversionErrorInterceptor.intercept(ConversionErrorInterceptor.java:122) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ParametersInterceptor.doIntercept(ParametersInterceptor.java:195) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.StaticParametersInterceptor.intercept(StaticParametersInterceptor.java:179) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.MultiselectInterceptor.intercept(MultiselectInterceptor.java:75) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.CheckboxInterceptor.intercept(CheckboxInterceptor.java:94) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.FileUploadInterceptor.intercept(FileUploadInterceptor.java:235) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ModelDrivenInterceptor.intercept(ModelDrivenInterceptor.java:89) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ScopedModelDrivenInterceptor.intercept(ScopedModelDrivenInterceptor.java:130) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.debugging.DebuggingInterceptor.intercept(DebuggingInterceptor.java:267) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ChainingInterceptor.intercept(ChainingInterceptor.java:126) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.PrepareInterceptor.doIntercept(PrepareInterceptor.java:138) com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:87) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.I18nInterceptor.intercept(I18nInterceptor.java:165) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.interceptor.ServletConfigInterceptor.intercept(ServletConfigInterceptor.java:164) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.AliasInterceptor.intercept(AliasInterceptor.java:179) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) com.opensymphony.xwork2.interceptor.ExceptionMappingInterceptor.intercept(ExceptionMappingInterceptor.java:176) com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:237) org.apache.struts2.impl.StrutsActionProxy.execute(StrutsActionProxy.java:52) org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:488) org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77) org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91) org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:190) org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:163) org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542) org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143) org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357) org.apache.coyote.ajp.AjpProcessor.service(AjpProcessor.java:433) org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893) org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1723) org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) java.lang.Thread.run(Thread.java:748)

You are seeing this page because development mode is enabled. Development mode, or devMode, enables extra debugging behaviors and reports to assist developers. To disable this mode, set:

struts.devMode=falsein your


WEB-INF/classes/struts.propertiesfile.

Creating the Web Application Project

In this exercise you will create a web application project and add the Hibernate libraries to the project. When you create the project, you will select Hibernate in the Frameworks panel of the New Project wizard and specify the database.

Choose File > New Project (Ctrl-Shift-N). Select Web Application from the Java Web category and click Next.

Type DVDStore for the project name and set the project location if needed.

De-select the Use Dedicated Folder option, if selected. Click Next.

For this tutorial there is little reason to copy project libraries to a dedicated folder because you will not need to share libraries with other users.

Set the server to GlassFish v3 and set the Java EE Version to Java EE 6 Web. Click Next.

Select the JavaServer Faces checkbox and use the default JSF 2.0 libraries.

Select the Hibernate 3.2.5 checkbox.

Select the sakila database from the Database Connection drop down list. Click Finish.

Note: If the sakila database is not available as an option in the Frameworks panel in the wizard, check to see if the connection is listed under the Databases node in the Services window. If the connection is not there, you need to create the database connection.

When you click Finish, the IDE creates the web application project and opens the hibernate.cfg.xml file and index.xhtml in the editor.

If you expand the Libraries node in the Projects window, you can see that the IDE added the Hibernate libraries to the project.

———————————————————————

Modifying the Hibernate Configuration File

When you create a new project that uses the Hibernate framework, the IDE automatically creates the hibernate.cfg.xml configuration file at the root of the context classpath of the application (in the Files window, src/java). The file is located in the

under the Source Packages node in the Projects window. The configuration file contains information about the database connection, resource mappings, and other connection properties. You can edit the file using the multi-view editor, or edit the XML directly in the XML editor.

In this exercise you will edit the default properties specified in hibernate.cfg.xml to enable debug logging for SQL statements and to enable Hibernate’s session context management.

Open hibernate.cfg.xml in the Design tab. You can open the file by expanding Source Packages >

in the Projects window and double-clicking hibernate.cfg.xml.

In the multi-view XML editor, expand the Configuration Properties node under Optional Properties.

Click Add to open the Add Hibernate Property dialog box.

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

Expand the Miscellaneous Properties node and click Add.

In the dialog box, select the properties hibernate.current_session_context_class and set the value to thread to enable Hibernate’s automatic session context management.

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

org.hibernate.dialect.MySQLDialect

com.mysql.jdbc.Driver

jdbc:mysql://localhost:3306/sakila

root

######

true

thread

Save your changes to the file.

You can close the file because you do not need to edit the file again.

Java, ORM & Hibernate 1 | Back to Main | Java, ORM & Hibernate 3

>> More Visual Web Pack Documentation

Using Hibernate With the NetBeans Visual Web Pack

Contributed by Chris
Kutler, Craig McClananan, and John Baker

May [Revision number: V5.5.1-1]

This tutorial shows you how to use the Hibernate framework in a NetBeans Visual Web Pack project. It also shows how to wrap
back end data with Option arrays and ObjectListDataProvider
objects for binding to JavaServer Faces components.

Examples used in this tutorial

» HibernateTravelPOJO.zip

This tutorial works with the following technologies and resources

JavaServer Faces Components/
Java EE Platform
1.2 with Java EE 5*1.1 with J2EE 1.4
Travel Database Required
BluePrints AJAX Component Library Not required

* As of the date this tutorial was published, only the Sun Java System Application Server supported Java EE 5.

This tutorial has been tailored for use with the Sun Java Application Server PE 9.0 Update Release 1 and with Tomcat 5.5.17.
If you are using a different server, consult the Release Notes and FAQs for known problems and workarounds.
For detailed information about the
supported servers and Java EE platform, see the Release Notes.

Binding the Components to the Data Wrappers

In this section, you bind the components to the data wrappers and add logic to synchronize the data in the Table component with the selected person.

  1. Open Page1 in the Visual Designer.
  2. Right-click the Drop Down List component and choose Bind to Data from the pop-up menu.
  3. In the Bind to an Object tab, select SessionBean1 > personOptions and click OK.
  4. Right-click the Table component and choose Table Layout from the pop-up menu.
  5. Choose tripDataProvider from the Get Data From drop-down list.

    Note: If tripDataProvider is not available from the drop-down list, build, close, and reopen the project, and try again.

  6. Select personId in the Selected list and click the left-arrow button to move the field from the Selected list to the Available list.
  7. Use the Up and Down buttons to arrange the remaining fields in the following order, as shown in Figure 6, and click OK.

    • tripId
    • depDate
    • depCity
    • destCity
    • tripTypeId
    Figure 6: Binding the Table Component to the

    tripDataProvider

    Wrapper
  8. In the Editing toolbar, click Java to open

    Page1.java

    in the Java Editor.
  9. In the

    prerender

    method, add the following code shown in bold.

    Code Sample 3:

    prerender

    Method

    public void prerender() {
    try {
    if (dropDown1.getSelected() == null ) {
    Option firstPerson = getSessionBean1().getPersonOptions()[0];
    getSessionBean1().getTripDataProvider().refreshTripsList(
    new Integer((String)firstPerson.getValue()));
    }
    } catch (Exception ex) {
    log(“Error Description”, ex);
    error(ex.getMessage());
    }
    }

    This code causes the page to display the information for the first person in the drop-down list when the user first visits the page.

  10. Right-click in the source and choose Fix Imports from the pop-up menu.

    The Fix Imports dialog appears.

  11. In the Fully Qualified Name drop-down list, select

    com.sun.webui.jsf.model.Option

    for Java EE 5
    projects and

    com.sun.rave.web.ui.model.Option

    for J2EE 1.4 projects.
  12. Click OK.
  13. Add the following code shown in bold to the

    dropDown1_processValueChange

    method.

    Code Sample 4:

    dropDown1_processValueChange

    Method

    public void dropDown1_processValueChange(ValueChangeEvent event) {
    try {
    Integer personId =
    new Integer((String)dropDown1.getSelected());
    getSessionBean1().getTripDataProvider().refreshTripsList(
    personId);
    } catch(Exception ex) {
    log(“Error getting Person List : “, ex);
    error(“Error getting Person List: ” + ex.getMessage());
    }
    }

    This code causes the page to display the trips for the selected person.

  14. In the main toolbar, click Run Main Project to run the project.
  15. Select a person’s name from the drop-down list to display that person’s trips.
HIbernate Tutorial using netbeans
HIbernate Tutorial using netbeans

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.

  1. Open


    DVDStoreAdmin.java

    and click the Source tab.

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


public DVDStoreAdmin() { initComponents(); } *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(); session.beginTransaction(); Query q = session.createQuery(hql); List resultList = q.list(); displayResult(resultList); session.getTransaction().commit(); } catch (HibernateException he) { he.printStackTrace(); } }

The

executeHQLQuery()

method calls Hibernate to execute the selected query. This method makes use of the

HibernateUtil.java

utility class to obtain the Hibernate Session.

  1. Right-click in the editor and choose Fix Imports (Ctrl-Shift-I; ⌘-Shift-I on Mac) to generate import statements for the Hibernate libraries (


    org.hibernate.Query

    ,

    org.hibernate.Session

    ) and

    java.util.List

    . Save your changes.

  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("")) { runQueryBasedOnFirstName(); } else if(!lastNameTextField.getText().trim().equals("")) { runQueryBasedOnLastName(); }* }

  1. Add the following method to display the results in the JTable.


private void displayResult(List resultList) { Vector

tableHeaders = new Vector

(); Vector tableData = new Vector(); tableHeaders.add("ActorId"); tableHeaders.add("FirstName"); tableHeaders.add("LastName"); tableHeaders.add("LastUpdated"); for(Object o : resultList) { Actor actor = (Actor)o; Vector
oneRow = new Vector
(); oneRow.add(actor.getActorId()); oneRow.add(actor.getFirstName()); oneRow.add(actor.getLastName()); oneRow.add(actor.getLastUpdate()); tableData.add(oneRow); } resultTable.setModel(new DefaultTableModel(tableData, tableHeaders)); }



  1. Right-click in the editor and choose Fix Imports (Ctrl-Shift-I; ⌘-Shift-I on Mac) to generate an import statement for


    java.util.Vector

    and

    java.util.List

    . Save your changes.

After you save the form you can run the project.

Creating a Hibernate Class Library

You begin this tutorial by downloading the Hibernate library files and using the Library Manager tool to make the required Hibernate libraries available to the IDE.

  1. Download

    hibernate-3.2.2.ga.zip

    from hibernate and extract the files. Note: The examples in this tutorial use Hibernate 3.2.2 and the associated JAR files that are provided with that version. If you use a different version, the JAR library names and version numbers might vary. In addition, the list of JAR libraries to add might differ.
  2. In the IDE, choose Tools > Library Manager from the main menu.
  3. Click New Library, type

    Hibernate322

    in the Library Name field, and click OK.
  4. Click Add JAR/Folder and navigate to the directory into which you extracted the Hibernate files.
  5. Select

    hibernate3.jar

    and press Enter.
  6. Click Add JAR/Folder again, and navigate into the

    lib

    subdirectory.
  7. Use Ctrl-Click to select the following 10 JAR files and press Enter. If you are using a different version than 3.2.2, consult Hibernate’s web site to determine which JAR files to select.


    • ant-1.6.5.jar

    • antlr-2.7.6.jar

    • asm-attrs.jar

    • asm.jar

    • cglib-2.1.3.jar

    • commons-logging-1.0.4.jar

    • commons-collections-2.1.1.jar

    • dom4j-1.6.1.jar

    • ehcache-1.2.3.jar

    • jdbc2_0-stdext.jar

    The following figure shows the Hibernate library in the Library Manager window.

    Figure 1: Library Manager Window Showing the Hibernate Library
  8. If you are deploying your application to the Tomcat server, you must
    also add

    jta.jar

    from the Hibernate

    lib

    directory.
  9. To make the Hibernate Javadoc available to the Java Editor, select the Javadoc tab, click Add Zip/Folder, navigate to the directory into which you extracted the Hibernate files, select the

    doc/api

    subdirectory, and press Enter.
  10. (Optional) If you want to step into Hibernate classes during a debugging session, click the Sources tab, click Add JAR/Folder, navigate to the directory into which you extracted the Hibernate files, select the

    src

    subdirectory, and press Enter.
  11. Click OK to close the Library Manager.
Hibernate example in netbeans
Hibernate example in netbeans

Troubleshooting Tips

If the web application is not working, here are some tips on how to diagnose the problem.

  • If, when you run the application, the table component displays “No
    items found,” make sure that the database server is running,
    that you have connected to the Travel database from the
    Runtime window,
    and that the port setting in the

    hibernate.cfg.xml

    file is correct. If you modify

    hibernate.cfg.xml

    , be
    sure to clean the project before rebuilding.
  • If the application throws

    java.lang.ExceptionInInitializerError
    HibernateTravelPOJO.HibernateUtil

    , ensure that the
    database is running. If you are deploying to the Tomcat
    server, make sure that you added the

    jta.jar

    to the Hibernate322 library.
  • If the table component does not display new data when you select
    a different person from the drop-down list, open the Design View on
    Page1, and verify that you selected the Auto-Submit on Change item
    from the pop-up menu for the Drop Down List component.
  • If the application throws

    java.lang.reflect.UndeclaredThrowableException
    at $Proxy64.createQuery(Unknown Source)

    , make sure that you
    have included the antlr-2.7.6 library and not the antlr-1.6.5 library.

See Also:

This page was last modified: May 24,

Hibernate

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.

Notes.

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

Creating the Reverse Engineering File

The reverse engineering file (

hibernate.reveng.xml

) is an XML file that can be used to modify the 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 how JDBC types are mapped to Hibernate types.

  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. Keep the default *


    src

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

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.

When you click Finish, the IDE generates the POJO

Actor.java

with all the required fields and generates a Hibernate mapping file 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 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.

  2. Expand the

    source package node in the Projects window.

  3. Right-click


    hibernate.cfg.xml

    and choose Run HQL Query to open the HQL Editor.

  4. Test the connection by typing


    from Actor

    in the HQL Query Editor. Click the Run HQL Query button () in the toolbar.

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

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

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

configure()

and 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 dvdrental for the package. Click Finish.

When you click Finish,

HibernateUtil.java

opens in the editor. You can close the file because you do not need to edit the file.

Modifying the Hibernate Configuration File

When you create a new project that uses the Hibernate framework, the IDE automatically creates the

hibernate.cfg.xml

configuration file at the root of the context classpath of the application (in the Files window,

src/java

). The file is located in the under the Source Packages node in the Projects window. The configuration file contains information about the database connection, resource mappings, and other connection properties. You can edit the file using the multi-view editor, or edit the XML directly in the XML editor.

In this exercise you will edit the default properties specified in

hibernate.cfg.xml

to enable debug logging for SQL statements and to enable Hibernate’s session context management.

  1. Open


    hibernate.cfg.xml

    in the Design tab. You can open the file by expanding thenode under Source Packages in the Projects window and double-clicking

    hibernate.cfg.xml

    .

  2. In the multi-view XML editor, 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

    . This enables the debug logging of the SQL statements.

  1. Expand the Miscellaneous Properties node and click Add.

  2. In the dialog box, select the


    properties hibernate.current_session_context_class

    and set the value to

    thread

    to enable Hibernate’s automatic session context management.

  1. Click Add again under the Miscellaneous Properties node and select


    hibernate.query.factory_class

    in the Property Name dropdown list.

  2. Select org.hibernate.hql.classic.ClassicQueryTranslatorFactory as the Property Value. Click OK.

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 (the three new properties are bold):



org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/sakila root ###### * true thread org.hibernate.hql.classic.ClassicQueryTranslatorFactory *


  1. Save your changes to the file.

You can close the file because you do not need to edit the file again.

Troubleshooting Tips

If the web application is not working, here are some tips on how to diagnose the problem.

  • If, when you run the application, the table component displays “No
    items found,” make sure that the database server is running,
    that you have connected to the Travel database from the
    Runtime window,
    and that the port setting in the

    hibernate.cfg.xml

    file is correct. If you modify

    hibernate.cfg.xml

    , be
    sure to clean the project before rebuilding.
  • If the application throws

    java.lang.ExceptionInInitializerError
    HibernateTravelPOJO.HibernateUtil

    , ensure that the
    database is running. If you are deploying to the Tomcat
    server, make sure that you added the

    jta.jar

    to the Hibernate322 library.
  • If the table component does not display new data when you select
    a different person from the drop-down list, open the Design View on
    Page1, and verify that you selected the Auto-Submit on Change item
    from the pop-up menu for the Drop Down List component.
  • If the application throws

    java.lang.reflect.UndeclaredThrowableException
    at $Proxy64.createQuery(Unknown Source)

    , make sure that you
    have included the antlr-2.7.6 library and not the antlr-1.6.5 library.

See Also:

This page was last modified: May 24,

Building Web Applications with Hibernate

In this topic, we use the NetBeans IDE to create and deploy a web application that displays data from a database. The web application uses the Hibernate framework as the persistence layer for retrieving and storing plain old Java objects (POJOs) to a relational database.

Hibernate is framework that provides tools for object relational mapping (ORM). The present topic demonstrates how to add support for the Hibernate framework to the IDE and create the necessary Hibernate files. After creating the Java objects and configuring the application to use Hibernate, we add a JSF managed bean and JSF 2.0 pages to display the data.

Softwares Used

To complete this topic, we will need the following software resources :—

  • NetBeans IDE 8.2
  • Java Development Kit (JDK) 8
  • GlassFish server 4.1.1
  • MySQL 5.0 with Type 4 driver
  • Sakila MySQL Sample Database Plugin

Developing Hibernate Application

We follow these steps one-by-one to create web application based on Hibernate.

Step 1: Creating the Database

This tutorial uses a MySQL database called sakila, a free sample MySQL database that is available from the MySQL site. The sakila database is not included when we install the IDE so we need to first create the database to follow this tutorial.

To create the sakila database we can download and install the Sakila Sample Database plugin using the Plugins manager. After we install the plugin the sakila database is added to the list of databases in the Create MySQL database dialog box. To get information on configuring the NetBeans IDE to work with MySQL, have a look at 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 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.

    When we click OK a Sakila node appears under the MySQL Server node.

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

When we click Connect a database connection node for the Sakila database (jdbc:mysql://localhost:3306/sakila [root on Default schema]) is listed under the Databases node. When a connection is open we can view the data in the database by expanding the connection node.

Step 2: Creating the Web Application Project

In this exercise we will create a web application project and add the Hibernate libraries to the project. When we create the project, we will select Hibernate in the Frameworks panel of the New Project wizard and specify the database.

  1. Choose File > New Project (Ctrl-Shift-N) from the main menu. Select Web Application from the Java Web category and click Next.
  2. Type DVDStore for the project name and set the project location.
  3. Deselect the Use Dedicated Folder option, if selected. Click Next.

    For this tutorial there is little reason to copy project libraries to a dedicated folder because we will not need to share libraries with other users.

  4. Set the server to the GlassFish Server and set the Java EE Version to Java EE 6 Web. Click Next.
  5. Select the JavaServer Faces checkbox and use the default JSF 2.2 libraries.
  6. Select the Hibernate 4.3.1 checkbox in the list of frameworks.
  7. Select the sakila database from the Database Connection drop down list. Click Finish.

Note: If the sakila database is not available as an option in the Frameworks panel in the wizard, check to see if the connection is listed under the Databases node in the Services window. If the connection is not there, we need to create the database connection.

When we click Finish, the IDE creates the web application project and opens the hibernate.cfg.xml file and index.xhtml in the editor.

If we expand the Libraries node in the Projects window, we can see that the IDE added the Hibernate libraries to the to the project.

Step 3: Modifying the Hibernate Configuration File

When we create a new project that uses the Hibernate framework, the IDE automatically creates the hibernate.cfg.xml configuration file at the root of the context classpath of the application (in the Files window, src/java). The file is located in the under the Source Packages node in the Projects window. The configuration file contains information about the database connection, resource mappings, and other connection properties. We can edit the file using the multi-view editor, or edit the XML directly in the XML editor.

In this exercise we will edit the default properties specified in hibernate.cfg.xml to enable debug logging for SQL statements and to enable Hibernate’s session context management.

  1. Open hibernate.cfg.xml in the Design tab. We can open the file by expanding the node under Source Packages in the Projects window and double-clicking hibernate.cfg.xml.
  2. In the multi-view XML editor, 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 property named hibernate.show_sql and set the value to true. This enables the debug logging of the SQL statements.
  5. Expand the Miscellaneous Properties node and click Add.
  6. In the dialog box, select the property hibernate.current_session_context_class and set the value to thread to enable Hibernate’s automatic session context management.

7. Click Add again under the Miscellaneous Properties node and select hibernate.query.factory_class in the Property Name dropdown list.

8. Select org.hibernate.hql.classic.ClassicQueryTranslatorFactory as the Property Value. Click OK.

If we click the XML tab in the editor we can see the file in XML view. Our file should look similar to the following (the 3 new properties are bold):


org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/sakila root system true thread org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory

9. Save the changes to the file.

We can close the file because we do not need to edit the file again.

Step 4: Creating the HibernateUtil.java Helper File

To use Hibernate we need to create a helper class that handles startup and that accesses Hibernate’s SessionFactory to obtain a Session object. The class calls configure() and loads the hibernate.cfg.xml configuration file and then builds the SessionFactory to obtain the Session object.

In this section we 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 dvdrental for the package. Click Finish.

When we click Finish, HibernateUtil.java opens in the editor. We can close the file because we don’t need to edit the file.

Step 5: Generating Hibernate Mapping Files and Java Classes

In this tutorial we use a POJO (plain old Java object) to represent the data in each of the tables in the database that we will use. The Java class specifies the fields for the columns in the tables and uses simple setters and getters to retrieve and write the data. To map the POJOs to the tables we can use a Hibernate mapping file or use annotations in the class.

We can use the Hibernate Mapping Files and POJOs from a Database wizard to create multiple POJOs and mapping files based on database tables. When using the wizard we select all the tables for which we want POJOs and mapping files and the IDE then generates the files for us based on the database tables and adds the mapping entries to hibernate.cfg.xml. When we use the wizard we can choose the files that we want the IDE to generate (only the POJOs, for example) and select code generation options (generate code that uses EJB 3 annotations, for example).

5.Creating the Hibernate Reverse Engineering File

If we want to use the Hibernate Mapping Files and POJOs from a Database wizard, we first need to create a hibernate.reveng.xml reverse engineering file. The Hibernate Mapping Files and POJOs from a Database wizard requires hibernate.reveng.xml and hibernate.cfg.xml.

The reverse engineering file enables us to have greater control over the database mapping strategy. The Hibernate Reverse Engineering Wizard creates a reverse engineering file with a default configuration that we can edit in the XML editor.

To create the Hibernate reverse engineering file, perform the following steps.

    1. Right-click the Source Packages node in the Projects window and choose New > Other to open the New File wizard.
    2. Select Hibernate Reverse Engineering Wizard in the Hibernate category. Click Next.
    3. Specify hibernate.reveng as the File Name and src/java for the Folder. Click Next.
    4. Select hibernate.cfg.xml from the Configuration File drop down list, if not selected.
    5. Select the following tables from Available Tables and click Add to add the tables to Selected Tables.

      • actor
      • category
      • film
      • film_actor
      • film_category
      • language

Click Finish.

The wizard generates a hibernate.reveng.xml reverse engineering file and opens the file in the editor. We can close the reverse engineering file because we don’t need to edit the file.

5.Creating the Hibernate Mapping Files and POJOs

We can use the Hibernate Mapping Files and POJOs from a Database wizard to generate files for we. The wizard can generate a POJO and a corresponding mapping file for each table that we select in the wizard. The mapping files are XML files that contain data about how the columns in the tables are mapped to the fields in the POJOs. We need to have the hibernate.reveng.xml and hibernate.cfg.xml files to use the wizard.

To create the POJOS and mapping files using a wizard, perform the following steps.

    1. Right-click 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. Ensure that the hibernate.cfg.xml and hibernate.reveng.xml files are selected in the drop down lists.
    4. Select JDK 5 Language Features under the “General Settings” options. Don’t choose the EJB 3 annotations here.
    5. Ensure that the Domain Code and Hibernate XML Mappings options under the “Code Generation Settings” are selected.
    6. Select dvdrental for the Package name. Click Finish.

When we click Finish the IDE generates POJOs and Hibernate mapping files with the fields mapped to the columns specified in hibernate.reveng.xml. The IDE also adds mapping entries to this file (shown in bold font).


org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/sakila root system true thread org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory

Note. Confirm that the mapping elements are listed after the property elements in the hibernate.cfg.xml file.

We can expand the dvdrental package to see the files generated by the wizard.

Step 6: Creating the FilmHelper.java Helper Class

We will now create a helper class in the dvdrental package that will be used to perform Hibernate queries on the database. We will use the Hibernate Query Language (HQL) editor to construct and test the queries for retrieving data. After we test the queries we will create methods in the helper class that construct and run the queries. We will then invoke the methods in the helper class from a JSF managed bean.

6.Creating the Helper Class

In this section we use the New File wizard to create the helper class FilmHelper.java in the dvdrental package. We will create a Hibernate session by calling getSessionFactory() in HibernateUtil.java and create some helper methods to create queries to retrieve data from the database. We will invoke the helper methods from the JSP pages.

    1. Right-click the dvdrental source package node and select New > Java Class to open the New File wizard.
    2. Type FilmHelper for the class name.
    3. Confirm that dvdrental is selected as the Package. Click Finish.
    4. Adding the following code (in bold) to create a Hibernate session.

      public class FilmHelper { Session session = null; public FilmHelper() { this.session = HibernateUtil.getSessionFactory().openSession(); } }

    5. Right-click in the editor and choose Fix Imports (Alt-Shift-I) to add any required import statements (org.hibernate.Session) and save the changes.

We will now modify FilmHelper.java to add methods that query the DB.

6.Enumerating Film Titles and Retrieving Actors Using an HQL Query

In this exercise, we will create a Hibernate Query Language (HQL) query that queries the database to retrieve a list of film titles from the Film table. We will then add a method that queries both the Actor and Film_actor tables to fetch the actors involved in a particular film.

The Film table has 1000 records so the method to retrieve the list of films should be able to retrieve records based on the filmId primary key. We will use the HQL editor to construct and test the HQL query. After we have created the correct query we will add a method to the class that can generate the proper query.

    1. Right-click the project node in the Projects window and choose Clean and Build.
    2. Right-click hibernate.cfg.xml in the Projects window and choose Run HQL Query to open the HQL query editor.
    3. Select hibernate.cfg from the drop down list in the toolbar.
    4. Test the connection by typing the following in the editor and clicking the Run HQL Query button ( ) in the toolbar.

      from Film

      When we click Run HQL Query we can see the results of the query in the bottom window of the HQL query editor.

      If we click the SQL button we can see the equivalent SQL query.

      select film0_.film_id as col_0_0_ from sakila.film film0_

    5. We now type the following query to retrieve the records in the Film table where the film id is between 100 and 200.

      from Film as film where film.filmId between 100 and 200

      The result window displays a list of records. Now that we have tested that the query returns the desired results, we can use the query in the helper class.

    6. Add the following method getFilmTitles() to FilmHelper.java to retrieve the films where the film id is between a certain range specified by the variables startID and endID.

      public List getFilmTitles(int startID, int endID) { List filmList = null; try { org.hibernate.Transaction tx = session.getTransaction();

      Query q = session.createQuery(“from Film as film where film.filmId between ‘” + startID + “‘ and ‘” + endID + “‘”);filmList = (List) q.list();session.getTransaction().commit(); }catch (Exception e) { e.printStackTrace(); } return filmList; }

    7. Add the following method getActorsByID() that retrieves the actors in a particular film. The method constructs the query using filmId as the input variable.

      public List getActorsByID(int filmId){ List actorList = null; try {

      org.hibernate.Transaction tx = session.getTransaction();Query q = session.createQuery(“from Actor as actor where actor.actorId in (select filmActor.actor.actorId from FilmActor as filmActor where filmActor.film.filmId='” + filmId + “‘)”);actorList = (List) q.list();session.getTransaction().commit();}catch (Exception e) {e.printStackTrace();} return actorList; }

    8. Fix the imports and save necessary changes.

      When we fix the imports we want to choose java.util.List and org.hibernate.Query.

6.Adding Additional Helper Methods

We will now add additional helper methods to FilmHelper.java to create queries based on an input variable. We can check the queries in the HQL query editor.

    1. Add the following method to retrieve a list of categories according to filmId.

      public Category getCategoryByID(int filmId){ List categoryList = null; try { org.hibernate.Transaction tx = session.getTransaction();

      Query q = session.createQuery(“from Category as category where category.categoryId in (select filmCat.category.categoryId from FilmCategory as filmCat where filmCat.film.filmId='” + filmId + “‘)”);categoryList = (List) q.list();session.getTransaction().commit(); }catch (Exception e) { e.printStackTrace(); } return categoryList.get(0); }

    2. We add the following method to retrieve a single film according to filmId.

      public Film getFilmByID(int filmId){ Film film = null; try { org.hibernate.Transaction tx = session.getTransaction();

      Query q = session.createQuery(“from Film as film where film.filmId=” + filmId);film = (Film) q.uniqueResult();session.getTransaction().commit(); }catch (Exception e) { e.printStackTrace(); } return film; }

    3. We add the following method to retrieve the film language according to langId.

      public String getLangByID(int langId){ Language language = null; try { org.hibernate.Transaction tx = session.getTransaction();

      Query q = session.createQuery(“from Language as lang where lang.languageId=” + langId);language = (Language) q.uniqueResult();session.getTransaction().commit(); }catch (Exception e) { e.printStackTrace(); } return language.getName(); }

    4. Save the changes.
  1. Add the following method to retrieve a list of categories according to filmId.
Step 7: Creating the JSF Managed Bean

In this step we will create a JSF managed bean. The methods in the managed bean are used for displaying data in the JSF pages and for accessing methods in the helper class to retrieve records. The JSF 2.0 specification enables us to use annotations in a bean class to identify the class as a JSF managed bean, to specify the scope and to specify a name for the bean.

To create the managed bean, perform the following steps.

  1. Right-click the dvdrental source package node and choose New > Other.
  2. Select JSF Managed Bean from the JavaServer Faces category. Click Next.
  3. Type FilmController for the Class Name.

    We will use the Managed Bean name filmController as the value for the inputText and commandButton in the JSF page index.xhtml when calling methods in the bean.

  4. Select dvdrental for the Package.
  5. Type filmController for the Name that will be used for the managed bean.
  6. Set Scope to Session. Click Finish.

When we click Finish, the IDE creates the bean class and opens the class in the editor. The IDE added the @Named and @SessionScoped annotations. We have also added the annotation @ManagedBean from javax.faces.bean.ManagedBean. See it below.

@Named(value = “filmController”)@ManagedBean@SessionScopedpublic class FilmController implements Serializable {/** Creates a new instance of FilmController */ public FilmController() { } }

After addting fields & methods and fixing the imports the final code would look like this:

package dvdrental;import javax.inject.Named;import javax.enterprise.context.SessionScoped;import java.io.Serializable;import java.util.List;import javax.faces.bean.ManagedBean;import javax.faces.model.DataModel;import javax.faces.model.ListDataModel;@Named(value = “filmController”)@ManagedBean@SessionScopedpublic class FilmController implements Serializable {int startId;int endId;DataModel filmTitles;FilmHelper helper;private int recordCount = 1000;private int pageSize = 10;private Film current;private int selectedItemIndex;/*** Creates a new instance of FilmController*/public FilmController() {helper = new FilmHelper();startId = 1;endId = 10;}public FilmController(int startId, int endId) {helper = new FilmHelper();this.startId = startId;this.endId = endId;}public Film getSelected() {if (current == null) {current = new Film();selectedItemIndex = -1;}return current;}public DataModel getFilmTitles() {if (filmTitles == null) {filmTitles = new ListDataModel(helper.getFilmTitles(startId, endId));}return filmTitles;}void recreateModel() {filmTitles = null;}public boolean isHasNextPage() {if (endId + pageSize <= recordCount) {return true;}return false;}public boolean isHasPreviousPage() {if (startId – pageSize > 0) {return true;}return false;}public String next() {startId = endId + 1;endId = endId + pageSize;recreateModel();return “index”;}public String previous() {startId = startId – pageSize;endId = endId – pageSize;recreateModel();return “index”;}public int getPageSize() {return pageSize;}public String prepareView() {current = (Film) getFilmTitles().getRowData();return “browse”;}public String prepareList() {recreateModel();return “index”;}public String getLanguage() {int langID = current.getLanguageByLanguageId().getLanguageId().intValue();String language = helper.getLangByID(langID);return language;}public String getActors() {List actors = helper.getActorsByID(current.getFilmId());StringBuffer totalCast = new StringBuffer();for (int i = 0; i < actors.size(); i++) {Actor actor = (Actor) actors.get(i);totalCast.append(actor.getFirstName());totalCast.append(” “);totalCast.append(actor.getLastName());totalCast.append(” “);}return totalCast.toString();}public String getCategory() {Category category = helper.getCategoryByID(current.getFilmId());return category.getName();}}

Step 8: Creating the Web Pages

In this exercise we will create two web pages for displaying the data. We will modify the index.xhtml generated by the IDE to add a table that displays the films in the database. We will then create browse.xhtml to display a film’s details when we click the “View” link in the table. We will also create a JSF template page that is used by index.xhtml and browse.xhtml.

8.Creating template.xhtml

We will first create the JSF Facelets template template.xhtml that is used in the composition of the index.xhtml and browse.xhtml pages.

    1. Right-click the DVDStore project node in the Projects window and choose New > Other.
    2. Select Facelets Template in the JavaServer Faces category. Click Next.
    3. Type template for the File Name and choose the first CSS layout style.
    4. Click Finish.

      When we click Finish, the file template.xhtml opens in the editor. The template contains the following default code. The color marked code within and will be replaced a little bit later.

      <br /> Facelets Template<br />


      Top

      Content

      5. Modify the

      element to change the default generated name to “body”.


      Content

      6. Save the changes.

The content enclosed within the element in index.xhtml and browse.xhtml will be inserted into the location identified with Content in the template. The CSS files also have to be added within

and

.

The final code would look like this:


xmlns:ui=”http://java.sun.com/jsf/facelets”xmlns:h=”http://java.sun.com/jsf/html”>

<br /> Facelets Template<br />


Top

Content

8.2 Modifying index.xhtml

When we created the web application, the IDE automatically generated the page index.xhtml. In this exercise we modify the page to display a list of film titles. The JSF page calls the methods in the JSF Managed Bean FilmController to retrieve the list of films and then displays a table with the film titles and descriptions.

    1. Expand the Web Pages folder in the Projects window and open index.xhtml in the editor.

      The New Project wizard generated the following default index.xhtml page.



      <br /> Facelet Title<br />


      Hello from Facelets

    2. Modify the page to use the JSF

      and

      elements and add a

      element.

      When we start typing the tags, the IDE adds xmlns:ui=”http://java.sun.com/jsf/facelets” tag library declaration.

      The

      and

      elements are used in combination with the page template that we will create. The

      element references the location of the template that will be used by this page. The

      element references the position in the template that the enclosed code will occupy.





    3. Add the following navigation links that call the previous and next methods in the JSF managed bean.
    4. Add the following dataTable element (in bold) to generate the table to display the retrieved items.
    5. Save the changes.
  1. Expand the Web Pages folder in the Projects window and open index.xhtml in the editor.

The index page will now display a list of film titles in the database. Each row in the table includes a “View” link that invokes the prepareView method in the managed bean. The prepareView method returns “browse” and will open browse.xhtml.

Note. When we type the

tag, the IDE will add xmlns:f=”http://java.sun.com/jsf/core tag library declaration. Confirm that the tag library is declared in the file.xmlns:f=”http://java.sun.com/jsf/core tag library declaration.

8.3 Creating browse.xhtml

We will now create the browse.xhtml page for displaying details of the selected film. We can use the Facelets Template Client wizard to create the page based on the JSF Facelets template template.xhtml that we created.

    1. Right-click DVDStore project node in the Projects window and choose New > Other.
    2. Select Facelets Template Client in the JavaServer Faces category. Click Next.
    3. Type browse for the File Name.
    4. Locate the Template for the page by clicking Browse to open the Browse Files dialog box.
    5. Expand the Web Pages folder and select template.xhtml. Click Select File.
    6. Select

      for the Generated Root Tag. Click Finish.

      When we click Finish, the file browse.xhtml opens in the editor with the following code.



      top


      body

      We can see that the new file specifies the template.xhtml file and that the tag

      has the property name=”body”

    7. Add the following code (in bold) between the

      tags to create the form and call the methods in the managed bean FilmController to retrieve the data and populate the form.



      top

      We can see that browse.xhtml and index.xhtml will use the same page template.

    8. Save the changes.
Step 9: Running the Project

The basics of the application are now complete. We can now run the application to check if everything is working correctly.

1. Click Run Main Project in the main toolbar or right-click the DVDStore application node in the Projects window and choose Run.

The IDE saves all changed files, builds the application, and deploys the application to the server. The IDE opens a browser window to the URL http://localhost:8484/DVDStore/ that displays the list of films.

2. In our browser, click “View” for the first one in the list to load browse.xhtml to view the film details.

Using Hibernate in a Web Application

This tutorial needs a review. You can edit it in GitHub following these contribution guidelines.
  • Creating the Database
  • Creating the Web Application Project
  • Modifying the Hibernate Configuration File
  • Creating the

    HibernateUtil.java

    Helper File
  • Generating Hibernate Mapping Files and Java Classes
  • Creating the

    FilmHelper.java

    Helper Class
  • Creating the JSF Managed Bean
  • Creating the Web Pages
  • Running the Project
  • See Also

In this tutorial, you use the NetBeans IDE to create and deploy a web application that displays data from a database. The web application uses the Hibernate framework as the persistence layer for retrieving and storing plain old Java objects (POJOs) to a relational database.

Hibernate is framework that provides tools for object relational mapping (ORM). The tutorial demonstrates how to add support for the Hibernate framework to the IDE and create the necessary Hibernate files. After creating the Java objects and configuring the application to use Hibernate, you create a JSF managed bean and JSF 2.0 pages to display the data.

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

  • Hibernate documentation at hibernate.org

To follow this tutorial, you need the following software and resources.

Software or Resource Version Required

7.1, 7.2, 7.3, 7.4, Java EE version

Version 6 or 7

GlassFish Server Open Source Edition

3.x or 4.x

Version 5.x

Sakila Database

Plugin available from update center

You can download a zip archive of the finished project.

Creating the Database

This tutorial uses a MySQL database called

sakila

, a free sample MySQL database that is available from the MySQL site. The sakila database is not included when you install the IDE so you need to first create the database to follow this tutorial.

To create the sakila database you can download and install the Sakila Sample Database plugin using the Plugins manager. After you install the plugin 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 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.

When you click OK a Sakila node appears 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.

Keywords searched by users: hibernate web application example in netbeans

Using Hibernate In A Web Application
Using Hibernate In A Web Application
Using Hibernate In A Web Application
Using Hibernate In A Web Application
Using Hibernate In A Java Swing Application
Using Hibernate In A Java Swing Application
Using Hibernate In A Web Application
Using Hibernate In A Web Application
Using Hibernate In A Web Application
Using Hibernate In A Web Application
Using Hibernate In A Web Application
Using Hibernate In A Web Application
Using Hibernate In A Web Application
Using Hibernate In A Web Application
Using Hibernate In A Web Application
Using Hibernate In A Web Application
Using Hibernate In A Java Swing Application
Using Hibernate In A Java Swing Application
Using Hibernate In A Java Swing Application
Using Hibernate In A Java Swing Application
Using Hibernate In A Web Application
Using Hibernate In A Web Application
Using Hibernate In A Web Application
Using Hibernate In A Web Application
How To Perform Basic Sql Operation Using Hibernate In Netbeans -  Whatinfotech
How To Perform Basic Sql Operation Using Hibernate In Netbeans – Whatinfotech
Using Hibernate In A Web Application
Using Hibernate In A Web Application
Login Form Using Jsp + Servlet + Hibernate + Mysql Example
Login Form Using Jsp + Servlet + Hibernate + Mysql Example
Jsp Servlet Hibernate Database Web Application (Registration Module) | Java  Guides - Youtube
Jsp Servlet Hibernate Database Web Application (Registration Module) | Java Guides – Youtube
How To Perform Basic Sql Operation Using Hibernate In Netbeans -  Whatinfotech
How To Perform Basic Sql Operation Using Hibernate In Netbeans – Whatinfotech
Kieu Trong Khanh: Hibernate 3.2.5 In Mvc Web Application With Netbean 6.9.1  And Mysql Server
Kieu Trong Khanh: Hibernate 3.2.5 In Mvc Web Application With Netbean 6.9.1 And Mysql Server
Using Hibernate In A Java Swing Application
Using Hibernate In A Java Swing Application

See more here: kientrucannam.vn

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *