HibernateAndWebApp

Using NetBeans for Building Hibernate Based Web Applications

Contents


Overview

Hibernate is a framework, which enables your applications to interact with DBs using Object Relational Mapping. In this tutorial, let us build a simple web application that depicts the Hibernate support provided by NetBeans 6.5 IDE. We will also learn about the auto completion, wizards and other code generation aids available.

The web application that we are going to build is a DVD Store application that allows user to browse and rent out DVD titles. This tutorial shows how you can use hibernate as a persistence layer and interact with the DB containing some sample DVD title information. For the purpose of this tutorial, we will be using the Sakila DB, a sample DB that you can download from the MySQL site. Information for setting up the Sakila DB is provided in the following sections.

Hibernate Support in NetBeans

Hibernate support for web application is available from NetBeans IDE 6.1. From NetBeans IDE 6.5 (NetBeans 6.5 IDE is not released yet. Please use latest dev. build), you can also reverse engineer DB tables to corresponding MFA Degree hibernate mapping files and Java classes using an intuitive wizard.

The following list enumerates the hibernate support in NetBeans IDE:

  • Wizard based creation of hibernate configuration file.
  • Wizard based creation of hibernate mapping file.
  • Reverse engineering support.
  • Support for creating POJO classes.
  • Code generation for hibernate utility class.
  • Code completion in hibernate mapping file and configuration file.
  • HQL Editor.

Requirements for This tutorial

To comprehend this tutorial, you need the following software:

  • NetBeans IDE 6.1 or higher – For reverse engineering tables, you need NetBeans IDE 6.5 or the latest development builds available from the Netbeans site.
  • Netbeans-Hibernate Plug-in – Hibernate support for web application is not available by default. You need to download the plug-in to activate this support. Instructions for downloading the plug-in are available in the following sections.
  • Sakila DBSakila DB is an optimized sample DB available from the MySQL site. Sakila DB has sample records that we can use in this tutorial. You can also create your own DB and try out this tutorial.

  • Note – This tutorial uses MySQL Server. But you can use any supported DB server with NetBeans IDE for working with Hibernate based applications.

Getting Started

The following sections of the tutorial shows you how you can set up the tutorial environment. The tutorial environment comprises the following components:

  • DB Setup – The tutorial uses Sakila MySQL DB. Hence you need to have a MySQL Server running in your machine.
  • NetBeans IDE Setup – You need to download the Hibernate plug-in.
  • Runtime Support – Since the tutorial focuses on building a web application, you need a server to deploy the web application. You can either use Apache Tomcat as a web server or can use Glassfish Application Server.

Setting up Sakila MySQL DB

The Sakila DB Schema and sample data can be downloaded from the MySQL site. Once you have downloaded and saved the DB bundle, extract the bundle to find 2 SQL files:

  • sakila-schema.sql
  • sakila-data.sql

Perform the following tasks, from the console/command line:

mysql –u root –p
<Enter MySQL root password.
mysql> source <path-to-sakila-schema.sql>
mysql> source <path-to-sakila-data.sql>

Sakila DB is now set up. For detailed instruction, refer to the MySQL Site. Once you have set up Sakila DB, from the NetBeans IDE, under Services tab, expand the Databases > MySQL Server at localhost:3306 node to find sakila entry as shown in the following figure:

File:HibernateAndWebApp/sakila nbview1 HibernateAndWebApp.png

Right click on sakila entry and click Connect to allow NetBeans IDE to establish the connection with the DB.

File:HibernateAndWebApp/sakila nbview2 HibernateAndWebApp.png

When you try to connect to Sakila DB, you will be prompted with a New Database Connection dialog box. Enter the MySQL connection information and click OK. If you are using WebStack in OpenSolaris OS, the default password for root is an empty string. For other platforms, provide the root password as applicable.

File:HibernateAndWebApp/sakila nbview3 HibernateAndWebApp.png

When NetBeans successfully connects with the DB, You can see the connection entry
jdbc:mysql://localhost:3306/sakila [RootOnDefaultSchema]
under the Databases node.

File:HibernateAndWebApp/sakila nbview4 HibernateAndWebApp.png

You can browse the tables available in the DB by expanding the Tables node.


  • Note – Creating DB Connection in NetBeans IDE is optional. You can perform this task even after setting up Hibernate support as shown later in this tutorial.

Now, we have successfully setup the DB for this tutorial. The next section deals with configuring NetBeans IDE to support Hibernate framework for web applications.

Setting up Hibernate Support

Plug-in for hibernate support can be downloaded and installed by performing the following tasks:

  1. Click Tools > Plugins
  2. Click Available Plugins Tab.
  3. In the Search field, enter Hibernate.
  4. Select Hibernate Support from the list and click Install.
  5. Accept the license terms and install the plug-in.

File:HibernateAndWebApp/nb65 plugin1 HibernateAndWebApp.png


  • Note – If you are using NetBeans IDE 6.1, you will see Hibernate Support and Hibernate 3.2.5 Library. If you install Hibernate Support plug-in, all necessary Hibernate libraries are also downloaded. When you build your application, these libraries are copied to
    WEB-INF/lib
    directory in the web application archive (.war) file.

Setting up Server Runtime

This tutorial shows you how you can build web applications using Hibernate framework. Hence you need a server to deploy and test the application. If you have installed NetBeans IDE as a complete bundle, Apache Tomcat Server and Glassfish Application Server are already bundled with the installer.

Go to Services Tab and expand Servers node to verify if one of these servers is present. If you do not find any server, Go to Tools > Servers to add a server. If you are using OpenSolaris OS, you can install the complete AMP runtime and NetBeans IDE by downloading and installing the
amp-dev
IPS package.

Building a DVD Rental Application

In the next couple of sections let us build a web application that depicts the usage of Hibernate persistence layer in NetBeans IDE. The application that we are going to build is a DVD Store, which lets you browse and rent out DVD titles.

Assuming that you have setup the tutorial environment, let us proceed with the project creation.

Creating a Web Application Project

In NetBeans IDE, you need to create a new web application project and add Hibernate support to it. You can also enable Hibernate support for an existing web application project by configuring the project properties. While creating a web application with Hibernate support, you will be asked to provide the DB connection information. The information provided by you will be used in the
hibernate.cfg.xml
file.

For creating a web application with Hibernate support, perform the following tasks:

  • Click File > New Project
  • Under Web Categories, click Web and select Web Application under Projects.
  • Click Next

File:HibernateAndWebApp/newproject1 HibernateAndWebApp.png

  • Enter DVDStore as the name of the project
  • Click Next

File:HibernateAndWebApp/newproject2 HibernateAndWebApp.png At the time of creating the project, you can specify the preferred runtime. You have the option of changing the Server at a later stage by configuring the project properties.

  • In the Server field, select Apache Tomcat 6.x Server
  • In the Java EE Version field, accept the default entry (Java EE 5).
  • Accept the context path as /DVDStore
  • Click Next

File:HibernateAndWebApp/newproject3 HibernateAndWebApp.png Now that we have created a web application, we can enable Hibernate support for the application.

  • From the Frameworks list, select Hibernate 3.2.5
  • In the Database Connection field, select
    jdbc:mysql://localhost:3306/sakila [RootOnDefaultSchema] 
  • Accept other default values
  • Click Finish

File:HibernateAndWebApp/newproject4 HibernateAndWebApp.png

Explore the DVDStore project tree. Hibernate configuration file
hibernate.cfg.xml
is created under Source Packages > <default package>. This is a simple XML file that you can edit at any stage of your project.

Hibernate Configuration File (
hibernate.cfg.xml
)

Hibernate configuration file created by NetBeans IDE contains DB connection information. When you need to connect to a different DB, you can edit this file to change the connection information.

Here is the snippet of
hibernate.cfg.xml
:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" 
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory name="session1">
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/sakila</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">root</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.current_session_context_class">thread</property>
  </session-factory>
</hibernate-configuration>

In the above mentioned snippet, we have added an additional property:

 <property name="hibernate.current_session_context_class">thread</property>

This is a required parameter to enable thread bound strategy for your hibernate configuration. For more information on Hibernate Sessions, read this document.

You can view the Hibernate configuration file using 2 views:

  1. Design View (Default view) – An intuitive interface for managing Hibernate configuration. You can set Session Factory and Security related properties with the help of GUI windows.
  2. XML View – If you are aware of the Hibernate configuration schema, you can directly use the XML View for adding/modifying properties.

In this tutorial, we are not going to manually add properties to this file to keep it simple. You will notice later in the tutorial that whenever we create Hibernate mapping files, this configuration file gets automatically updated.

Creating Java Classes

Sakila DB has a table by name film. We need to create a corresponding Java class (POJO) with fields corresponding to the columns available in the film table.

To create the Java class, perform the following tasks:

  • Right click DVDStore project and select New > Java Class
  • Enter Class Name as Film
  • Enter Package name as dvdrental
  • Accept the defaults
  • Click Finish

File:HibernateAndWebApp/pojo1 HibernateAndWebApp.png

Now that we have created the Film class, we need to add fields corresponding to the columns in the film table. You need not map all of the available columns in the table. Expand Source Packages > dvdrental to find the file Film.java. Make changes to the file as highlighted in the following snippet:

package dvdrental;

import java.io.Serializable;

public class Film implements Serializable {

    private int filmID;
    private String title;
    private String description;
    private String releaseYear;
    private Integer languageID;
    private Integer origLangID;
    private Integer rentalDuration;
    private Float rentalRate;
    private Integer length;
    private String rating;
    private String specialFeatures;
    private String lastUpdate;

}

Now you can add getters and setters for the fields. You don’t need to manually do this. Just right click on Film.java file and select Insert Code > Getters and Setters. Select all the check boxes and click Generate to generate the getters and setters for the variables.


  • Note – Some records in the film table of Sakila DB has NULL values for original_language_id column. Hence you need to use a wrapper class (Integer) and not primitive type (int) while mapping fields.

File:HibernateAndWebApp/pojo2 HibernateAndWebApp.png

Now take a look at the modified file:

public class Film implements Serializable {
    private int filmID;
    private String title;
    private String description;
    private String releaseYear;
    private Integer languageID;
    private Integer origLangID;
    private Integer rentalDuration;
    private Float rentalRate;
    private Integer length;
    private String rating;
    private String specialFeatures;
    private String lastUpdate;

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public int getFilmID() {
        return filmID;
    }

    public void setFilmID(int filmID) {
        this.filmID = filmID;
    }

    public Integer getLanguageID() {
        return languageID;
    }

    public void setLanguageID(Integer languageID) {
        this.languageID = languageID;
    }

    public String getLastUpdate() {
        return lastUpdate;
    }

    public void setLastUpdate(String lastUpdate) {
        this.lastUpdate = lastUpdate;
    }

    public Integer getLength() {
        return length;
    }

    public void setLength(Integer length) {
        this.length = length;
    }

    public Integer getOrigLangID() {
        return origLangID;
    }

    public void setOrigLangID(Integer origLangID) {
        this.origLangID = origLangID;
    }

    public String getRating() {
        return rating;
    }

    public void setRating(String rating) {
        this.rating = rating;
    }

    public String getReleaseYear() {
        return releaseYear;
    }

    public void setReleaseYear(String releaseYear) {
        this.releaseYear = releaseYear;
    }

    public Integer getRentalDuration() {
        return rentalDuration;
    }

    public void setRentalDuration(Integer rentalDuration) {
        this.rentalDuration = rentalDuration;
    }

    public Float getRentalRate() {
        return rentalRate;
    }

    public void setRentalRate(Float rentalRate) {
        this.rentalRate = rentalRate;
    }

    public String getSpecialFeatures() {
        return specialFeatures;
    }

    public void setSpecialFeatures(String specialFeatures) {
        this.specialFeatures = specialFeatures;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }   
}


  • Note – In NetBeans 6.5 IDE, you do not need to manually create Java Class files. You can choose to create a Hibernate Reverse Engineering File as shown in the next section.

OR Mapping

In the previous section, we have created the class film.java. Now we need to map our class to the film table using a Hibernate mapping file. The mapping file is an XML file that contains ORM metadata that defines how the class fields are mapped to table columns and primary keys. We will create Hibernate mappings file for other some tables in Sakila DB in this tutorial.

In this section, we use the New File wizard to create a simple File.hbm.xml Hibernate mapping file for File.java class. You then need to edit the file in the XML editor to map the fields in the class to corresponding columns in the film table . You can use the IDE’ code completion feature to help you edit the mapping file.

To map film table to Film.java, perform the following tasks:

  • Right Click dvdrental package and select New File > Other
  • Click Hibernate under Categories section and select Hibernate Mapping File
  • Click Next

File:HibernateAndWebApp/nb65 newmapping HibernateAndWebApp.png


  • Note – In NetBeans 6.5 IDE, you do not need to manually create the mapping file. You can choose Driving Instructors Twickenham to create a Hibernate Reverse Engineering File as shown in the next section.

  • Enter Film.hbm as the name of the mapping file
  • Click Next

File:HibernateAndWebApp/mapping2 HibernateAndWebApp.png

  • Click button in the Class to Map field to open the Find Type dialog box
  • Search and Select Film (dvdrental) type and click OK

File:HibernateAndWebApp/mapping3 HibernateAndWebApp.png

  • In the Database Table drop down box, select the film table
  • Verify if the Configuration File field has hibernate.cfg.xml value
  • Click Finish

File:HibernateAndWebApp/mapping4 HibernateAndWebApp.png

Just like the Hibernate configuration file, code completion is available for hibernate mapping file too.

The following figures show code completion feature for the hibernate mapping file:

File:HibernateAndWebApp/hbmaid1 HibernateAndWebApp.png

File:HibernateAndWebApp/hbmaid2 HibernateAndWebApp.png

Make changes to
Film.hbm.xml file
to map the fields as shown in the snippet below:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class dynamic-insert="false" dynamic-update="false" mutable="true" name="dvdrental.Film" 
optimistic-lock="version" polymorphism="implicit" select-before-update="false" table="film">
        <id column="film_id" name="filmID">
            <generator class="increment"/>
        </id>
        
        <property column="description" name="description"/>
        <property column="language_id" name="languageID"/>
        <property column="last_update" name="lastUpdate"/>
        <property column="length" name="length"/>
        <property column="original_language_id" name="origLangID"/>
        <property column="rating" name="rating"/>
        <property column="release_year" name="releaseYear"/>
        <property column="rental_duration" name="rentalDuration"/>
        <property column="rental_rate" name="rentalRate"/>
        <property column="special_features" name="specialFeatures"/>
        <property column="title" name="title"/>
        
    </class>
</hibernate-mapping>

In this section, we created a mapping file for the film table, but for our sample, we need to create similar mapping files for other Sakila tables including actor, category and language tables. We will use the reverse engineering feature available from NetBeans IDE 6.5 to map these tables as shown in the next section.

Reverse Engineering (NetBeans 6.5)

Starting from NetBeans IDE 6.5, you do not need to manually create the POJO classes or the mapping files. You can create a reverse engineering configuration file
hibernate.reveng.xml
that contains the necessary mappings.

For creating a Hibernate reverse engineering file, perform the following tasks:

  • Right click dvdrental source package and select New File > Other
  • Under Hibernate category, select Hibernate Reverse Engineering File
  • Click Next

File:HibernateAndWebApp/nb65 newreverse HibernateAndWebApp.png

  • Enter File Name as hibernate.reveng
  • Accept the defaults and click Next

File:HibernateAndWebApp/nb65 newreverse2 HibernateAndWebApp.png

Now you need to choose the tables for which you need to map.

  • From the Available Tables, select actor, category, language, film_actor, and film_category and click Add>
  • Click Next

File:HibernateAndWebApp/nb65 newreverse3 HibernateAndWebApp.png

  • In the General Settings, click Java5 Syntax as our project is a simple web application and does not contain any EJB
  • In the Code Generation Settings, select both Domain Code and Hibernate XML Mappings since we need to generate both the Java classes and the mapping files
  • Accept other default values
  • Click Finish

File:HibernateAndWebApp/nb65 newreverse4 HibernateAndWebApp.png

Now check your
hibernate.cfg.xml
file to see the mappings in place:

    ....
    <mapping resource="dvdrental/Language.hbm.xml"/>
    <mapping resource="dvdrental/Actor.hbm.xml"/>
    <mapping resource="dvdrental/FilmActor.hbm.xml"/>
    <mapping resource="dvdrental/FilmCategory.hbm.xml"/>
    <mapping resource="dvdrental/Category.hbm.xml"/>
    ....

Connecting to DB Using Hibernate Utility

Now that we have created the mapping files, we need to create a helper class that can access Hibernate’s SessionFactory to obtain a Session object so that we can load Film and other objects. You can generate the helper class by performing the following tasks:

  • Right click dvdrental source package and select New File > Other
  • Under Hibernate category, select HibernateUtil.java
  • Click Next
  • Provide HibernateUtil as the File Name
  • Click Finish

File:HibernateAndWebApp/nb65 newutil HibernateAndWebApp.png

The following code snippet shows the content of the
HibernateUtil.java
file. We won’t be modifying this file in this tutorial.

package dvdrental;

import org.hibernate.cfg.Configuration;
import org.hibernate.SessionFactory;

public class HibernateUtil {
    private static final SessionFactory sessionFactory;
    static {
        try {
            // Create the SessionFactory from standard (hibernate.cfg.xml) 
            // config file.
            sessionFactory = new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Log the exception. 
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
}

Creating Helper Application

In the last section, we created a utility class for connecting to DB. We will be creating another helper class in the dvdrental package that will be used to perform Hibernate queries on the DB.

For creating this helper class, perform the following tasks:

  • Right click dvdrental source package and select New > Java Class
  • Enter FilmHelper as the Class Name
  • Click Finish

In the FilmHelper.java file, we will be adding helper methods to query the DB as shown in the following sections. Refer to the dvdrental/FilmHelper.java for the complete code.

Enumerating DVD Titles (Using HQL)

We will be using Hibernate Query Language (HQL) to query records from the DB. Film table in Sakila DB has 1000 records hence the method that we create should be able to retrieve records based on the filmid primary key.

In FilmHelper.java, add the following method:

    public List getFilmTitles(int startID, int endID) {
        List<Film> filmList = null;
        try {            
            org.hibernate.Transaction tx = session.beginTransaction();
            Query q = session.createQuery 
	("from Film as film where film.filmID between '"+startID+"' and '"+endID+"'");
            filmList = (List<Film>) q.list();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return filmList;
    }

Enumerating Actors (Using HQL Sub Queries)

In the last section, we used a simple HQL query to enumerate records. Let us add one more method to fetch the actors involved in a particular film by querying multiple tables using sub queries.

The example shown in the following snippet shows a sub query for fetching records from both actor and film_actor table:

    public List getActorsByID(int filmID){
        List<Actor> actorList = null;
        try {
            org.hibernate.Transaction tx = session.beginTransaction();
            Query q = session.createQuery
            ("from Actor as actor where actor.actorID in 
	(select actorID from FilmActor filmActor where    
            filmActor.filmID='"+filmID+"')");
            actorList = (List<Actor>) q.list();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return actorList;
    }

Introduction to HQL Editor (NetBeans 6.5 IDE)

The examples provided in the previous sections showed you how you can use the Hibernate Query Language (HQL) to get a list of DVD titles and the corresponding actors. You can also use the new HQL Editor from NetBeans 6.5 IDE to construct your HQL queries and sub-queries before using it in your application. You can define and execute HQL queries for testing purposes.

To invoke the HQL Editor, perform the following tasks:

  • Right click hibernate.cfg.xml file and select Run HQL Query

File:HibernateAndWebApp/hqleditor1 HibernateAndWebApp.png

The following figure shows the HQL editor. The top panel contains the text area where you can build driving Schools Twickenham your HQL queries. For executing the query, click on the icon with a green arrow mark (next to the session field) as shown in the figure.

File:HibernateAndWebApp/hqleditor2 HibernateAndWebApp.png

You can also view the correponding SQL query by clicking the SQL button.

FilmHelper.java

The following code is the complete listing of the utility class:

package dvdrental;

import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;

public class FilmHelper {
    
    Session session = null;

    public FilmHelper() {
        this.session = HibernateUtil.getSessionFactory().getCurrentSession();
    }

    public List getFilmTitles(int startID, int endID) {
        List<Film> filmList = null;
        try {            
            org.hibernate.Transaction tx = session.beginTransaction();
            Query q = session.createQuery
	("from Film as film where film.filmID between '"+startID+"' and '"+endID+"'");
            filmList = (List<Film>) q.list();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return filmList;

    }
    
    public List getActorsByID(int filmID){
        List<Actor> actorList = null;
        try {
            org.hibernate.Transaction tx = session.beginTransaction();
            Query q = session.createQuery
	("from Actor as actor where actor.actorID in 
	(select actorID from FilmActor filmActor where filmActor.filmID='"+filmID+"')");
            actorList = (List<Actor>) q.list();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return actorList;
    }
    
    public Category getCategoryByID(int filmID){
        List<Category> categoryList = null;
        try {
            org.hibernate.Transaction tx = session.beginTransaction();
            Query q = session.createQuery
	("from Category as category where category.categoryID in 
	(select categoryID from FilmCategory filmCat where filmCat.filmID='"+filmID+"')");
            categoryList = (List<Category>) q.list();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return categoryList.get(0);
    }
    
    public Film getFilmByID(int filmID){
        
        Film film = null;
        List<Film> filmList = null;
        
        try {
            org.hibernate.Transaction tx = session.beginTransaction();
            Query q = session.createQuery
	("from Film as film where film.filmID='"+filmID+"'");
            filmList = (List<Film>) q.list();
            film = (Film) filmList.get(0);
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return film;
    }
    
    public String getLangByID(int langID){
        
        String language = null;
        List<Language> langList = null;
        
        try {
            org.hibernate.Transaction tx = session.beginTransaction();
            Query q = session.createQuery
	("from Language as lang where lang.languageID='"+langID+"'");
            langList = (List<Language>) q.list();
            language = ((Language) langList.get(0)).getName();
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return language;
    }
}

We will be invoking the methods in this class from the JSP files we build in the next section.

Creating the Web Interface

So far, we have created the Java classes, utility files, mapping files, and other Hibernate configuration files. Now we will create 2 JSP files-
browse.jsp
and {index.jsp} to show sample records from the DB.

To create the JSP file, perform the following tasks:

  • Right click on the DVDStore node and select New > JSP
  • Enter browse.jsp as the name of the JSP file
  • Click Finish
In
browse.jsp
file add the following snippet:

<%
            //Get title ID
            int filmID = 1;
            if (request.getParameter("id") != null) {
                filmID = Integer.parseInt(request.getParameter("id"));
            }
%>
<%
            boolean startPage = false;
            boolean endPage = false;
                
            FilmHelper helper = new FilmHelper();
            Film film = helper.getFilmByID(filmID);

            String filmTitle = film.getTitle();
            String filmDescription = film.getDescription();
            
            //Get Actors
            List actors = helper.getActorsByID(filmID);
            StringBuffer totalCast = new StringBuffer();
            
            //Get Category
            Category category = helper.getCategoryByID(filmID);
            String catName = category.getName();
            
            for(Iterator it=actors.iterator();it.hasNext();){
                Actor actor = (Actor)it.next();
                totalCast.append(actor.getFirstName());
                totalCast.append(" ");
                totalCast.append(actor.getLastName());
                totalCast.append("  ");
            }

            int langID = film.getLanguageID();
            String language = helper.getLangByID(langID);
            int filmLength = film.getLength();
            String filmRating = film.getRating();
            String filmYear = film.getReleaseYear();

            int rentalDuration = film.getRentalDuration().intValue();
            float rentalRate = film.getRentalRate().floatValue();
            String specialFeatures = film.getSpecialFeatures();
            
            …..
%>

Check the source of index.jsp for the complete code. Also this tutorial does not show you how to create Style sheets (CSS). Download the tutorial bundle and check out these files.

Also check out the code of
index.jsp
that displays the available DVDs.

Running the Application

For running the web application, you need to have a web server running. You can use either the bundled Tomcat Server or the Glassfish Application Server.

  • Download the DVDStore project and open the project in NetBeans IDE 6.5.
  • Right click the DVDStore node and select Build.
  • After the build process is complete, right click the DVDStore node and select Run.

If the web browser does not start automatically, access the application at:

http://localhost:8080/DVDStore/

The following figure shows the main page. Click any title to view the DVD information.

File:HibernateAndWebApp/dvdstore1 HibernateAndWebApp.PNG

Detailed information about the DVD is displayed on this page. Click Rent Out to rent out the DVD.

File:HibernateAndWebApp/dvdstore2 HibernateAndWebApp.PNG

Troubleshooting

The following sections lists some issues that you might face while running the DVDStore application.

MySQL Driver Not Found

If you get an error stating that MySQL driver not available or not in the classpath, perform the following tasks:

  • Right click DVDStore node and click Properties
  • Click Libraries from the Categories section
  • Click Add Library, select MySQL JDBC Driver and click OK

File:HibernateAndWebApp/prereq1 HibernateAndWebApp.png

OutOfMemoryError: PermGen Space

This error may occur when you are deploying DVDStore application to Apache Tomcat Server. This problem occurs with driving lessons enfield long running JVMs. More information can be found in this thread. This is a development/interoperability issue and can be fixed by changing the target server. You can change the target server from Apache Tomcat to GlassFish Application Server.

Download the Sample

File:DVDStore HibernateAndWebApp.zip DVD Store Sample Project - This link is broken

In
hibernate.cfg.xml
, you need to modify the MySQL connection information to make the application work.

Reference


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