>> 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.
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.
- 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.
- Create a Java Class Library project (POJO project) that segregates the Hibernate persistence code for the database tables into a reusable Hibernate front end.
- Add the database driver and the required Hibernate libraries to the POJO project.
- Develop a Visual Web Application project that references the POJO project and the Hibernate libraries.
- Use wrapper classes to connect the components to the Hibernate persistence classes.
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.
- 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.
- In the IDE, choose Tools > Library Manager from the main menu.
- Click New Library, type
Hibernate322 in the Library Name field, and click OK.
- Click Add JAR/Folder and navigate to the directory into which you extracted the Hibernate files.
- Select
hibernate3.jar and press Enter.
- Click Add JAR/Folder again, and navigate into the
lib subdirectory.
- 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 |
- If you are deploying your application to the Tomcat server, you must
also add
jta.jar from the Hibernate lib directory.
- 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.
- (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.
- Click OK to close the Library Manager.
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.
- Extract the contents of the
HibernateTravelPOJO.zip file into the
NetBeansProjects folder under your home directory, or into directory of your choice.
- In the IDE, close any open projects.
- Choose File > Open Project, and open the HibernateTravelPOJO project.
- In the Projects window, expand the HibernateTravelPOJO node, right-click the Libraries node, and choose Add Library from the pop-up menu.
- In the Add Library dialog box, select Hibernate322 and click Add Library.
- Right-click the Libraries node again, and choose Add JAR/Folder from the pop-up menu.
-
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.
-
Press Enter.
The database driver is now available for Hibernate connections to the database.
-
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.
- In the Projects window, right-click the HibernateTravelPOJO node and choose Build Project.
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 |
- In the Runtime window, expand the Databases node.
-
Right-click the jdbc node for the Travel database and choose Connect
from the pop-up menu.
- In the Connect dialog box, enter
travel
for the Password,
select Remember Password During This Session, and click OK.
- From the main menu, choose File > New Project.
- In the New Project Wizard, select Web from the Categories list and select
Visual Web Application from the Projects list.
- Click Next.
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.
- In the Projects window, right-click HibernateTutorialApp > Libraries and choose Add Library.
-
In the Add Library window, select Hibernate322 and click Add Library, as shown in the following figure.
Figure 4: Adding the Hibernate Library |
- Right-click HibernateTutorialApp > Libraries again,
and choose Add Project.
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 |
- Drag a Drop Down List component from the Palette and drop it in the top left corner of Page1 in the Visual Designer.
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.
- Click Design in the editing toolbar to switch back to the Visual
Designer.
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.
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.
- Drag and drop a Table component below the Drop Down List component.
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.
-
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.
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.
-
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.
-
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;
}
} |
-
Right-click in the source and choose Fix Imports from the pop-up menu.
The Fix Imports dialog appears.
-
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 |
- Close and save the file.
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.
- In the Projects window, right-click HibernateTutorialApp >
Source Packages > hibernatetutorialapp and choose New > Java Class.
-
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.
-
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<Trip> tripsList = new ArrayList<Trip>();
/** 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();
}
}
} |
- Right-click in the source and choose Fix Imports from the pop-up menu.
-
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 |
- Close and save the file.
- In the Outline window, right-click the SessionBean1 node and choose Add > Property from the pop-up menu.
- In the New Property Pattern dialog box, type
tripDataProvider in the Name text box, type TripDataProvider in the Type text box, and click OK.
- Double-click the SessionBean1 node to open the
SessionBean1.java source file.
-
In the Navigation window, double-click the tripDataProvider node.
The IDE scrolls the source code to the declaration for the tripDataProvider property.
-
Replace the declaration for the tripDataProvider property with the following statement:
private TripDataProvider tripDataProvider = new TripDataProvider();
- Press F11 to build the project.
-
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.
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.
- Open Page1 in the Visual Designer.
- Right-click the Drop Down List component and choose Bind to Data from the pop-up menu.
- In the Bind to an Object tab, select SessionBean1 > personOptions and click OK
.
- Right-click the Table component and choose Table Layout from the pop-up menu.
-
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.
- Select personId in the Selected list and click the 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 in Figure 6, and click OK.
- tripId
- depDate
- depCity
- destCity
- tripTypeId
Figure 6: Binding the Table Component to the tripDataProvider Wrapper |
- In the Editing toolbar, click Java to open
Page1.java in the Java Editor.
-
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.
-
Right-click in the source and choose Fix Imports from the pop-up menu.
The Fix Imports dialog appears.
- 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.
- Click OK.
-
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.
- In the main toolbar, click Run Main Project to run the project.
- Select a person's name from the drop-down list to display that person's trips.
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,
|
|