>> More Visual Web Pack Documentation
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.
Note: This document uses the NetBeans IDE 5.5 Release. If you are using NetBeans IDE 6.x, see Using Hibernate in a Visual Web JSF Application. For more information, see the Hibernate Demo for NetBeans IDE.
Expected duration: 40 minutes
Examples used in this tutorial
This tutorial works with the following technologies and resources
1.2 with Java EE 5*
1.1 with J2EE 1.4
Required
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 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.
hibernate-3.2.2.ga.zip from www.hibernate.org 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.jarThe following figure shows the Hibernate library in the Library Manager window.

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

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

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

In the Add Project window, navigate to and choose HibernateTravelPOJO, and click Add Project JAR Files, as shown in the following figure.

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.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.
Double-click the SessionBean1 node to open the SessionBean1.java source file.
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.
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.
Query org.hibernate.QuerySession org.hibernate.SessionList java.util.ListIterator java.util.IteratorOption com.sun.webui.jsf.model.Option for Java EE 5com.sun.rave.web.ui.model.Option for J2EE 1.4Transaction org.hibernate.TransactionObjectListDataProvider class to build a TripDataProvider wrapper for the results from a trips query.Name the class TripDataProvider and click Finish.
TripDataProvider class.
Replace the class definition with the following code.
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();
}
}
}
Select the following fully qualified names, and click OK.
Session org.hibernate.SessionTransaction org.hibernate.TransactionSet java.util.SettripDataProvider 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.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.

tripDataProvider WrapperPage1.java in the Java Editor.
In the prerender method, add the following code shown in bold.
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());
}
}
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, selectcom.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.
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());
}
}
If the web application is not working, here are some tips on how to diagnose the problem.
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:
You are viewing a mobilized version of this site...
View original page here