HibernateAndVisualWebProject


Contents


Using Hibernate in Visual Web Project in NetBeans 6.1

You can find a version of this tutorial on netbeans.org at Using Hibernate in a Visual Web JSF Application

The Hibernate Support plugin is available at beta update center for NetBeans 6.1. This tutorial shows you how to use Hibernate as the persistence layer in a Visual Web Project to retrieve/store data from/to the Travel sample database.

Installing Hibernate Support Plugin

The Hibernate Support plugin is not installed as part of the base product. Go through the following steps to install it.

  • Go to main menu Tools > Plugins

Image:pluginMenu_HibernateAndVisualWebProject.jpg

  • In the Plugins dialog, click on Available Plugins tab and check Hibernate 3.2.5 Library and Hibernate Support.

Image:installPlugin_HibernateAndVisualWebProject.jpg

  • Click Install button at the bottom.
  • Follow the steps and install the 2 plugins.

Creating a Visual Web Project With Hibernate Framework

In this section, you create a Web project with Visual JavaServer Faces and Hibernate Frameworks.

  • From the main menu, choose File > New Project.
  • In the New Project Wizard, select Web from the Categories list and select Web Application from the Projects list.
  • Click Next.
  • Name the project HibernateTravelApp and click Next.
  • Select the Server and Java EE Version Java EE 5, and click Next
  • In the Frameworks list, check Visual Web JavaServer Faces and Hibernate 3.2.5, as showing below.

Image:frameworks_HibernateAndVisualWebProject.jpg

  • Click Finish.
A default Hibernate configuration file hibernate_HibernateAndVisualWebProject.cfg.xml is created.
The necessary Hibernate jars are automatically added in the project.

Image:hibernatelibrary_HibernateAndVisualWebProject.jpg

Modifying Hibernate Configuration file

In this section, you add two more optional properties to the configuration file. There are two ways to edit the file. You can use the visual editor (Design tab) or edit the XML file directly with code completion. The steps below use the Design tab.

  • Click on the hibernate_HibernateAndVisualWebProject.cfg.xml tab, then the Design tab.
  • Expand the Optional Properties > Configuration Properties node.
  • Click Add button. Add property hibernate.show_sql with value true.
This enables the debug logging of the SQL statements.
  • Expand the Optional Properties > Miscellaneous Properties node. Add properties hibernate.current_session_context_class with value thread.
This enables Hibernate's automatic session context management.

That's all for the configuration file. Your configuration file should look like the attached hibernate_HibernateAndVisualWebProject.cfg.xml file.

Creating POJOs

In this section, you create two plain old Java objects (POJOs): Person_HibernateAndVisualWebProject.java and Trip_HibernateAndVisualWebProject.java.

  • In the Projects window, right click on the Source Packages node and select New > Java Class...
  • Name the class Person and enter Package travel.
  • Click Finish.
  • Copy and paste code from the attached Person_HibernateAndVisualWebProject.java file.
Note
Person must implement java.io.Serializable and must has a default public constructor Person()
public class Person implements java.io.Serializable {
    
    /** Creates a new instance of Person */
    public Person() {
    }

    ...

}
  • Right click on the Source Packages > travel node and select New > Java Class...
  • Name the class Trip. Make sure the package is travel
  • Click Finish.
  • Copy and past code from the attached Trip_HibernateAndVisualWebProject.java file.
Note
Trip must implement java.io.Serializable and must has a default public constructor Trip()
public class Trip implements java.io.Serializable {
    
    /** Creates a new instance of Trip */
    public Trip() {
    }

    ...

}

Now the Java classes are ready to be mapped.

Mapping the POJOs

You create two mapping files in this section to map Person to database table PERSON and Trip to table TRIP.

  • Right click on Source Packages > travel node and select New > Other...
  • In the wizard, select Hibernate from the Categories list and Hibernate Mapping File from the File Types list, as shown below.

Image:newMapping_HibernateAndVisualWebProject.jpg

  • Click Next.
  • Name the mapping file Person.hbm. Make sure the Folder is src/java/travel.
  • Click Next.
  • Click on the ... button next to the Class to Map field. Type in Person and select the travel.Person from this project.
  • Make sure the Configuration File is hibernate_HibernateAndVisualWebProject.cfg.xml
  • Select Database Table PERSON.
Note
if the Database Table combo box drop down is empty, then leave it blank here. You can enter the table name later in the XML directly.
  • Click Finish.
A Person_HibernateAndVisualWebProject.hbm.xml is created in the same location as the class Person.
  • In the XML editor for the Person_HibernateAndVisualWebProject.hbm.xml, using code completion to map the id, properties and the one-to-many relationship. See the attached mapping file Person_HibernateAndVisualWebProject.hbm.xml.
Note
It is a good idea to validate the mapping file by right-clicking on the Person_HibernateAndVisualWebProject.hbm.xml node the Projects window and select Validate XML.
Note
It is a good idea to validate the mapping file by right-clicking on the Trip_HibernateAndVisualWebProject.hbm.xml node in the Projects window and select Validate XML.

Creating HibernateUtil Helper Class

Before you can load and store some Person and Trip objects, you need to complete the setup with some infrastructure code. In this section you create a HibernateUtil helper class, which takes care of startup and makes accessing a SessionFactory convenient.

  • In the Projects window, right click on Source Packages > travel node and select New > Other...
  • In the wizard dialog, select Hibernate from the Categories list and HibernateUtil.java from the FileTypes list as below.

Image:newUtil_HibernateAndVisualWebProject.jpg

  • Click Next.
  • Name the class HibernateUtil and click Finish.

That's all for the helper class. No further modification is needed.

The infrastructure is complete. The Source code in your project should look like the following: Image:projectSrc_HibernateAndVisualWebProject.jpg

Now we are ready to do some real work using Hibernate.

Creating the Visual Web Page

In this section, you create a Visual Web Page as showing below Image:page1-designtime_HibernateAndVisualWebProject.jpg

  • Open the Visual Designer for the Page1.
  • Drag a Drop Down List component from the Palette and drop it in the top left corner of Page1.
  • 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.
  • Right-click on the Drop Down List component again and select Add Binding Attribute.
  • 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.

Retrieving Data From the Database Using Hibernate Framework

In this section, you add business logic to the session bean so that your project can access the data source using the Hibernate framework.

  • Open SessionBean1_HibernateAndVisualWebProject.java by double-clicking on the SessionBean1 node.
  • In the Java editor, find an empty space (for example, right before the constructor) and right-click; then select Insert Code... > Add Property...
  • In the Add Property dialog, name the property personOptions and enter Type Option[[[ | []], and click OK.

Image:addPersonOptions_HibernateAndVisualWebProject.jpg

The getter and setter for property personOptions are generated in SessionBean1_HibernateAndVisualWebProject.java. Don't worry about the read wiggly lines just yet. They'll be fixed shortly.
  • Repeat the above steps to add another property named selectedPersonId with Type Integer.

Image:addSelectedPersonId_HibernateAndVisualWebProject.jpg

  • Repeat the steps one more time to add a property named trips4Person with Type Trip[[[ | []].

Image:addTrips4Person_HibernateAndVisualWebProject.jpg

  • Add the following two private methods in the SessionBean1 class.
The first method calls a query on the Person data source and stores the results in the personOptions array. The second method updates the trips for the selected person.
    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]);
    }
  • Right-click in the source and choose Fix Imports from the pop-up menu. The Fix Imports dialog appears. Select the fully qualified names as shown below, and click OK.

Image:fixImports_HibernateAndVisualWebProject.jpg

  • Call method buildPersonOptions() at the end of init() (Note:not _init()) in the SessionBean1 class.
    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 initialiation code here
        
        // <editor-fold defaultstate="collapsed" desc="Managed Component Initialization">
        // Initialize automatically managed components
        // *Note* - this logic should NOT be modified
        try {
            _init();
        } catch (Exception e) {
            log("SessionBean1 Initialization Failure", e);
            throw e instanceof FacesException ? (FacesException) e: new FacesException(e);
        }
        
        // </editor-fold>
        // Perform application initialization that must complete
        // *after* managed components are initialized
        // TODO - add your own initialization code here
        
        // Fill in the personOptions[]
        buildPersonOptions();
    }
  • Call method updateTrips4Person() at the end of setSelectedPersonId() in the SessionBean1 class.
    public void setSelectedPersonId(Integer selectedPersonId) {
        this.selectedPersonId = selectedPersonId;
        updateTrips4Person();
    }
  • Build the project.

Here is the finish SessionBean1_HibernateAndVisualWebProject.java file.

Binding Components to Data

In this section, you bind the Drop Down List and Table components to the properties defined in the previous section.

  • Open the Visual Designer for Page1.
  • Right click on the Drop Down List component and select Property Bindings...
  • In the dialog, select items in the bindable property list and SessionBean1 > personOptions in the binding target list. Click Apply.

Image:bindingItems_HibernateAndVisualWebProject.jpg

  • In the same dialog, select selected in the bindable property list and SessionBean1 > selectedPersonId in the binding target list. Click Apply.

Image:bindingSelected_HibernateAndVisualWebProject.jpg

  • Click Close.
  • 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.

Image:tableLayout_HibernateAndVisualWebProject.jpg

  • In the Editing toolbar, click Java to open Page1.java in the Java Editor.
  • In the prerender method, add the following code.
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.
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());
        }
    }
  • 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, as shown below.

Image:fixImportsOption_HibernateAndVisualWebProject.jpg

That's all for coding!

Note
if you get an error saying "can not find symbol: variable dropDown1", that means you forget to Add Binding Attribute for the Drop Down List component. Go back to the Designer, right click on the Drop Down List component and select Add Binding Attribute.

Deploying the Web Application

Click on the green arrow button to deploy the project. This is what you should see in your browser. Image:webapp_HibernateAndVisualWebProject.jpg

Select a different person in the Drop Down List to see the content of the table changing.

Other

  • If you want to demo this tutorial to someone, here are some points you can talk about.
Not logged in. Log in, Register

By use of this website, you agree to the NetBeans Policies and Terms of Use. © 2012, Oracle Corporation and/or its affiliates. Sponsored by Oracle logo