当前页面: 开发资料首页 → Netbeans 专题 → Using Hibernate With the NetBeans Visual Web Pack
摘要: 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 |
![]() ![]() | |||
Travel Database | ![]() |
|||
BluePrints AJAX Component Library | ![]() |
* 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.Hibernate322
in the Library Name field, and click OK. hibernate3.jar
and press Enter.lib
subdirectory.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 |
jta.jar
from the Hibernate lib
directory.
doc/api
subdirectory, and press Enter.
src
subdirectory, and press Enter.
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 |
NetBeansProjects
folder under your home directory, or into directory of your choice.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.
![]() Figure 3: HibernateTutorialApp Page1 |
travel
for the Password,
select Remember Password During This Session, and click OK. Name the project HibernateTutorialApp
, select
the Server and Java EE Version, and click Finish.
Page1
) open in the Visual Designer.
In the Add Library window, select Hibernate322 and click Add Library, as shown in the following figure.
![]() Figure 4: Adding the Hibernate Library |
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 |
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.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.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.
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 5com.sun.rave.web.ui.model.Option for J2EE 1.4 |
Transaction |
org.hibernate.Transaction |
ObjectListDataProvider
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.
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(); } } } |
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 |
tripDataProvider
in the Name text box, type TripDataProvider
in the Type text box, and click OK.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();
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.![]() Figure 6: Binding the Table Component to the tripDataProvider Wrapper |
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()); } } |
Right-click in the source and choose Fix Imports from the pop-up menu.
The Fix Imports dialog appears.com.sun.webui.jsf.model.Option
for Java EE 5
projects and
com.sun.rave.web.ui.model.Option
for J2EE 1.4 projects.
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()); } } |
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.
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.
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: