站内搜索: 请输入搜索关键词

当前页面: 开发资料首页Netbeans 专题Using Hibernate With the NetBeans Visual Web Pack

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

Contents

Hibernate and the NetBeans Visual Web Pack
Creating a Hibernate Class Library
Preparing the Hibernate Front End to the Database
Creating a Visual Web Project That Uses the Hibernate Framework
Adding an Option Array Wrapper for the Person List
Adding the Object List Data Provider Wrapper for the Trips List
Binding the Components to the Data Wrappers
Troubleshooting Tips
  Content on this page applies to NetBeans 5.5 Visual Web Pack

Examples used in this tutorial

» HibernateTravelPOJO.zip

This tutorial works with the following technologies and resources

JavaServer Faces Components/
Java EE Platform
works with1.2 with Java EE 5*
works with1.1 with J2EE 1.4
Travel Database requiredRequired
BluePrints AJAX Component Library not requiredNot 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.
  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.

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

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

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

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.

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<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();
            }
        }
    }
  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.

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

Troubleshooting Tips

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


See Also:



>> More Visual Web Pack Documentation

This page was last modified:  February 26, 2007



↑返回目录
前一篇: Using the Ajax Map Viewer Component
后一篇: Using Databound Components to Access a Database