Using Hibernate in a Visual Web JSF Application
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 add Visual Web JSF components to a web page to display the data.
Before starting this tutorial you may want to familiarize yourself with
using Hibernate and with Visual Web JSF components.
You can see a screencast of this tutorial at Hibernate Demo for NetBeans IDE.
Note: This document uses the NetBeans IDE 6.1 Release. If you
are using NetBeans IDE 6.5, see Using Hibernate in a Visual Web JSF Application in NetBeans IDE 6.5.
Contents
To follow this tutorial, you need the following software and resources.
| NetBeans IDE |
Web & Java EE version 6.1 |
| Java Development Kit (JDK) |
Version 6 or
version 5 |
JavaServer Faces Components/
Java EE Platform |
1.2 with Java EE 5* or
1.1 with J2EE 1.4
|
| GlassFish Application Server |
V2 |
| Hibernate Plugin |
available from NetBeans Update Center |
| Travel Database |
yes |
You can download the solution to this tutorial from the
Hibernate Travel App Plugin page
on the Plugin Portal.
Adding Hibernate Support to the IDE
To integrate support for Hibernate into the IDE, you need to install the Hibernate plugins that are available from
the NetBeans Beta Update Center. The Beta update center contains two plugins for Hibernate.
You can skip this section if you already installed the Hibernate plugins.
You can check the Installed tab of the Plugins manager to see the plugins that are installed.
- Choose Tools > Plugins from the main menu.
- In the Available Plugins tab, select the following plugins and click Install.
- Hibernate Support
- Hibernate 3.2.5 Library
- Step through the wizard to install the plugins.
Installing the Hibernate plugins adds support for creating Hibernate files and adding
Hibernate libraries to web projects.
Creating the Web Application Project
In this exercise you will create a Visual Web JSF project and add the Hibernate libraries to the project.
When you create the project, you will select the Visual Web JSF and Hibernate in the Frameworks panel of the New Project wizard.
You will also specify the database.
- Choose File > New Project (Ctrl-Shift-N).
Select Web Application from the Web category and click Next.
- Type HibernateTravelApp for the project name and set the project location.
- 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.
Click Next.
- Set the server to GlassFish and set the Java EE Version to Java EE 5. Click Next.
- Select the Visual Web JavaServer Faces checkbox.
- Select the Hibernate 3.2.5 checkbox.
- Use the default session name (session1) and ensure that the travel database is selected for the
Database Connection and the Connection URL. Click Finish.
Note: The IDE comes with a sample Travel database and a pre-configured connection to the database.
If the travel 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 Page1 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, WEB-INF/classes).
The file is located under the Configuration Files 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 the Configuration Files node in the Projects window and double-clicking hibernate.cfg.xml.
- 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:
<hibernate-configuration>
<session-factory name="session1">
<property name="hibernate.dialect">org.hibernate.dialect.DerbyDialect</property>
<property name="hibernate.connection.driver_class">org.apache.derby.jdbc.ClientDriver</property>
<property name="hibernate.connection.url">jdbc:derby://localhost:1527/travel</property>
<property name="hibernate.connection.username">travel</property>
<property name="hibernate.connection.password">travel</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.current_session_context_class">thread</property>
</session-factory>
</hibernate-configuration>
- Save your changes to the file.
Creating Java Objects
In this tutorial you use two plain old Java objects (POJOs), Person and Trip,
to represent the data in the tables PERSON and TRIP in the travel database.
Each of the classes specifies fields for the columns in the tables and uses simple setters and getters to retrieve and
write the data. After you create the classes you will then need to map the classes to the tables.
Create the Person Java Class
- Right-click the Source Packages node in the Projects window and choose New > Java Class to open the New Java Class wizard.
- In the wizard, type Person for the class name and type travel for the package. Click Finish.
- Make the following changes (displayed in bold) to the class to implement the Serializable interface and add fields for the table columns.
public class Person implements Serializable {
private int personId;
private String name;
private String jobTitle;
private boolean frequentFlyer;
private java.util.Set trips;
}
- Generate the getters and setters for the fields by right-clicking in the Source Editor, choosing Insert Code (Alt-Insert) and then selecting Getter and Setter.
- 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 Person item and then hit the Space bar to select all fields in Person.
- Fix your imports and save your changes.
Create the Trip Java Class
- Right-click the Source Packages node in the Projects window and choose New > Java Class to open the New Java Class wizard.
- In the wizard, type Trip for the class name and type travel for the package. Click Finish.
- Make the following changes (displayed in bold) to implement the Serializable interface and add fields for the table columns to the class.
public class Trip implements Serializable {
private int tripId;
private int personId;
private Date depDate;
private String depCity;
private String destCity;
private int tripTypeId;
}
- Generate the getters and setters for the fields by right-click in the Source Editor, choosing Insert Code (Alt-Insert) and then selecting Getter and Setter.
- In the Generate Getters and Setters dialog box, select all the fields and click Generate.
- Fix your imports and save your changes.
You can close Person.java and Trip.java because you will not need to edit the files again.
Mapping the Classes to the Database Tables
Now that you have the classes to represent the tables, you need to map each persistent class to the respective
table using a Hibernate mapping file.
The mapping file is an XML file that contains ORM metadata that defines how the class fields are mapped to
table columns and primary keys.
You will create a Hibernate mapping file for each of the classes.
In this section you use the New File wizard to create a simple .hbm.xml Hibernate mapping file for each of the classes.
You then will edit the file in the XML editor to map the fields in each class to the column in the
corresponding table and to set additional properties.
You can use the IDE's code completion to help you edit the mapping file.
Mapping Person.java to the PERSON table
First you will create the Hibernate mapping file Person.hbm.xml to map the
fields in Person.java to columns in the PERSON table.
- Start the JavaDB database server.
- In the Projects window, right-click the travel node under Source Packages and select New > Other in the popup menu to open the New File wizard.
- Select Hibernate from the Categories list and Hibernate Mapping File from the File Types list. Click Next.
- Type Person.hbm for the file name and set the folder to src/java/travel. Click Next.
- Type travel.Person for the Class to Map.
Note: Alternatively, you can click the Browse button and type Person in the Find Type dialog.
- Select PERSON from the Database Table drop-down list.
Note: If the Database Table drop-down list is empty, that probably means that the
database is not running. You can continue and create the file without specifying the table,
but you need to remember to supply the table in the XML.
- Click Finish.
When you click Finish, the IDE creates the Person.hbm.xml file in the same source package as Person.java
and opens the file in the editor.
By default, the XML file looks like the following:
<hibernate-mapping>
<class dynamic-insert="false" dynamic-update="false" mutable="true"
name="travel.Person" optimistic-lock="version" polymorphism="implicit"
select-before-update="false" table="PERSON"/>
</hibernate-mapping>
Note: If you were unable to select the PERSON table in the drop-down list when you created the file,
be sure to add table="PERSON" to the class element.
- In the XML editor, make the following changes (displayed in bold) to map the ID, properties and the one-to-many relationship.
<hibernate-mapping>
<class dynamic-insert="false" dynamic-update="false"
mutable="true" name="travel.Person" optimistic-lock="version"
polymorphism="implicit" select-before-update="false" table="PERSON">
<id column="PERSONID" name="personId">
<generator class="increment"/>
</id>
<property column="NAME" name="name"/>
<property column="JOBTITLE" name="jobTitle"/>
<property column="FREQUENTFLYER" name="frequentFlyer"/>
<set cascade="all-delete-orphan" inverse="true" lazy="true" name="trips" table="TRIP">
<key column="PERSONID"/>
<one-to-many class="travel.Trip"/>
</set>
</class>
</hibernate-mapping>
You can use the code completion in the XML editor to help you add properties and values.
If the code completion is not working for you as in this screenshot, see the note below.
Note: By default, the class element has a closing tag.
Because you need to add property elements between the opening and closing class elements,
you need to make the following changes (displayed in bold).
After making the changes you can then use code completion between the class elements.
<hibernate-mapping>
<class dynamic-insert="false" dynamic-update="false"
mutable="true" name="travel.Person" optimistic-lock="version"
polymorphism="implicit" select-before-update="false" table="PERSON">
</class>
</hibernate-mapping>
- Validate the XML, fix any validation errors and save your file.
Mapping Trip.java to the TRIP Table
You will now create the Hibernate mapping file Trip.hbm.xml to map the
fields in Trip.java to columns in the TRIP table.
- In the Projects window, right-click the travel node under Source Packages and select New > Other in the popup menu to open the New File wizard.
- Select Hibernate from the Categories list and Hibernate Mapping File from the File Types list. Click Next.
- Type Trip.hbm for the file name and set the folder to src/java/travel. Click Next.
- Type travel.Trip for the Class to Map.
Note: Alternatively, you can click the Browse button and type Trip in the Find Type dialog.
- Select TRIP from the Database Table drop-down list.
Note: If the Database Table drop-down list is empty, then leave it blank here.
You can enter the table name later in the XML editor.
- Click Finish.
When you click Finish, the IDE creates Trip.hbm.xml in the same folder as the class Trip.java
and opens the file in the editor.
- In the XML editor, make the following changes (in bold).
<hibernate-mapping>
<class dynamic-insert="false" dynamic-update="false" mutable="true"
name="travel.Trip" optimistic-lock="version" polymorphism="implicit"
select-before-update="false" table="TRIP">
<id column="TRIPID" name="tripId">
<generator class="increment"/>
</id>
<property column="PERSONID" name="personId"/>
<property column="DEPDATE" name="depDate" type="date"/>
<property column="DEPCITY" name="depCity"/>
<property column="DESTCITY" name="destCity"/>
<property column="TRIPTYPEID" name="tripTypeId"/>
</class>
</hibernate-mapping>
Use the code completion in the XML editor to help you add properties and values.
- Validate the XML, fix any validation errors and save your file.
Creating the Hibernate Helper Class
To use Hibernate you need to create a helper class that handles startup
and that accesses Hibernate's SessionFactory to obtain a Session object so that you can load and store Person and Trip objects.
The helper class first calls Configuration() to load the hibernate.properties file.
The class then calls configure() and loads the hibernate.cfg.xml configuration file.
Finally, the helper class builds the SessionFactory to obtain the Session object.
In this section you use the New File wizard to create the helper class HibernateUtil.java.
- Right-click the travel source package node and select New > Other to open the New File wizard.
- Select Hibernate from the Categories list and HibernateUtil.java from the File Types list. Click Next.
- Type HibernateUtil for the class name. Click Finish.
When you click Finish, the class opens in the editor.
You can close the file because you do not need to edit the file.
You now have all the classes for your application.
If you expand the Source Packages node in the Projects window, your project should look like the following screenshot.
Creating the Visual Web JSF Page
Now that the classes are created, you can create the web pages for displaying and modifying the data.
You will create a JSP page that uses the JSF framework and Visual Web JSF components that you bind to the objects.
Adding the Visual Web JSF Components to the Page
- Expand the Web Pages folder in the Projects window and open Page1.jsp in the Visual Designer.
- Drag a Drop Down List component from the Woodstock Basic component set in the Palette and drop it in the top left corner of Page1.
- Right-click the Drop Down List component and choose 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.
- Right-click the Drop Down List component again and choose Add Binding Attribute.
Note: You will specify the property bindings later in the tutorial.
NetBeans IDE 6.1 features on-demand binding.
Where components require Java coding, you must manually add the binding attribute to components in a
Visual Web JSF application. To do so, right-click each component and choose Add Binding Attribute.
For more information, see the
On-demand Binding Attribute Wiki.
- Drag and drop a Table component below the Drop Down List component.
- Drag and drop a Message Group component below the Table component.
Message Group components help you to diagnose runtime problems.
By default, the Message Group component displays messages about runtime errors,
validation errors, and conversion errors.
- Save your changes.
Your web page now has the necessary components. You now need to bind the components to the data source.
Accessing the Data Source from SessionBean1
You now need to edit SessionBean1 to access the data source.
In this exercise use the Add Property dialog box to specify the fields in SessionBean1 and to generate the
getters and setters for the fields. The Session Bean opens a session context and then retrieves the data
via the Java objects.
- Expand the hibernatetravelapp source package in the Projects window and double-click SessionBean1.java to open the file in the editor.
- Place the cursor in an empty space in the source code (for example, right after the constructor) and right-click and
choose Insert Code > Add Property (Ctrl-I) to open the Add Property dialog box.
- In the Add Property dialog box, type personOptions for the Name, type Option[] for the Type and select private.
- Select Generate Getters and Setters, if unselected. Click OK.
- Repeat the steps to add the following properties:
| selectedPersonId |
Integer |
| trips4Person |
Trip[] |
- Add the methods buildPersonOptions and updateTrips4Person to the class by adding the following (in bold) to SessionBean1 after the getApplicationBean1 method.
protected ApplicationBean1 getApplicationBean1() {
return (ApplicationBean1) getBean("ApplicationBean1");
}
private void buildPersonOptions() {
List<Person> personList = null;
try{
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
Transaction tx = session.beginTransaction();
Query q = session.createQuery("from Person");
personList = (List<Person>) q.list();
} catch(Exception e) {
e.printStackTrace();
}
personOptions = new Option[personList.size()];
int i=0;
for(Person person : personList) {
Option opt = new Option(person.getPersonId(), person.getName());
personOptions[i++] = opt;
}
}
private void updateTrips4Person() {
if(selectedPersonId == null ) {
trips4Person = new Trip[1];
trips4Person[0] = new Trip();
return;
}
Set personTrips = null;
try{
Session session =
HibernateUtil.getSessionFactory().getCurrentSession();
Transaction tx = session.beginTransaction();
Person person = (Person)session.load(Person.class, selectedPersonId);
personTrips = (PersistentSet)person.getTrips();
} catch(Exception e) {
e.printStackTrace();
}
trips4Person = (Trip[]) personTrips.toArray(new Trip[0]);
}
The buildPersonOptions method calls a query on the Person data source and stores the results in the personOptions array.
The updateTrips4Person method updates the trips for the selected person.
- Fix your imports.
Note: When you select the fully qualified names to import, make sure you select the org.hibernate libraries and
com.sun.webui.jsf.model.Option and java.util.Set.
- Call method buildPersonOptions by adding the following (in bold) at the end of the init() method.
@Override
public void init() {
super.init();
try {
_init();
} catch (Exception e) {
log("SessionBean1 Initialization Failure", e);
throw e instanceof FacesException ? (FacesException) e : new FacesException(e);
}
// Fill in the personOptions[]
buildPersonOptions();
}
- Call the method updateTrips4Person by adding the following (in bold) at the end of the setSelectedPersonId method.
public void setSelectedPersonId(Integer selectedPersonId) {
this.selectedPersonId = selectedPersonId;
updateTrips4Person();
}
- Save your changes.
- Right-click the project node in the Projects window and choose Build.
Binding Components to Data
In this section, you bind the Drop Down List and Table components in the web page to the properties
defined in the previous section in SessionBean1.
- Open Page1.jsp in the Visual Designer.
- Right click the Drop Down List component and choose Property Bindings to open the Property Bindings dialog window.
- Select items in the bindable property list and personOptions (under the SessionBean1 node) in the binding target list.
Click Apply.
- In the same dialog, select selected in the bindable property list and selectedPersonId (under the SessionBean1 node) in the binding target list.
Click Apply.
- Click Close to close the dialog window.
- In the Visual Designer, right click on the Table component and select Table Layout.
- In the dialog, choose trips4Person (SessionBean1) from the Get Data From drop-down list.
Note: If you do not see trips4Person (SessionBean1) in the drop-down list, most likely is because you forgot to build the project at the end of the previous section.
- Select personId in the Selected list and click the left-arrow button Left Arrow Button to move the field from the Selected list to the Available list.
- Use the Up and Down buttons to arrange the remaining fields in the following order, as shown below, and click OK.
- In the Editing toolbar, click Java to open Page1.java in the Java Editor.
- In the prerender method, add the following code (displayed in bold).
public void prerender() {
try {
if (dropDown1.getSelected() == null ) {
Option firstPerson = getSessionBean1().getPersonOptions()[0];
getSessionBean1().setSelectedPersonId((Integer)firstPerson.getValue());
}
} catch (Exception ex) {
log("Error Description", ex);
error(ex.getMessage());
}
}
The code in the prerender method is invoked before a web browser starts to display the page.
Adding the code to the prerender method causes the page to display the information for the first person
in the drop-down list when the user first visits the page.
When the browser first requests the page, the application creates an
instance of Page1 and calls the prerender method. The server sends the response
(the HTML page) and the Page1 instance is destroyed. The application does
not call the value change event handler, because the application
only generates value change events when a page is submitted (in this case, when a new person is selected).
- Right-click in the source and choose Fix Imports from the popup menu to open the Fix Imports dialog box.
In the Fully Qualified Name drop-down list, select com.sun.webui.jsf.model.Option, as shown below.
- Save your changes.
Running the Project
Click Run Main Project in the main toolbar.
The IDE saves all changed files, rebuilds the application, and deploys the application
to the server.
- Select a person from the drop-down list to see how the contents of the table are updated with the data for the selected person.
Installing the Sample Plugin
You can download the solution project for this tutorial by downloading the
Hibernate Travel App Plugin
from the Plugin Portal.
After you install the plugin, a sample project is added to the Visual Web samples available in the New Project wizard.
Before you can run the sample application, you need to add the Hibernate and JSF libraries to the project.
You also need to have an instance of the Glassfish application server registered with the IDE.
You need to install the Hibernate plugins before you can add the Hibernate libraries to the project.
Complete the following steps to download the plugin, create the sample project and add the required Hibernate and JSF libraries.
- Choose Tools > Plugins to open the Plugins manager.
- Select the Hibernate Travel App Sample in the Available Plugins tab. Click Install.
After you click Install, step through the Plugin installer to install the plugin.
When you see the warning that the sample app plugin is not signed, click Continue.
- Choose File > New Project from the main menu to open the New Project wizard.
- Select Samples > Web > Visual JSF in the Categories pane and select Hibernate Travel App Sample. Click Next.
- Specify the Project Location. Click Finish.
When you click Finish, the IDE creates the project and displays project in the Projects window.
The project will not compile as it is because some of the libraries are missing.
If you expand the project's Libraries node in the Projects window, you can see that the necessary
Hibernate and JSF libraries are missing.
- Right-click the Libraries node and choose Add Library from the popup menu.
The Add Library dialog box displays the available libraries.
- Click Import to open the Import Library dialog box.
- Select the following Global Libraries:
- Hibernate
- JSF 1.1/1.2 Support
- Web UI Components
- Web UI Default Theme
You can select multiple libraries by holding the ctrl button when you select the libraries.
Click Import Library.
- Make sure the correct libraries are selected in the Add Library dialog and click Add Library.
When you click Add Library, the IDE displays the added libraries below the Libraries node in the Projects window.
After you add the required libraries, the compilation error badges on your source files will disappear.
- Right-click the project node and choose Run.
When you click Run the IDE builds the application and deploys the application to the server.
The default web page opens in your browser window.
See Also