Escolar Documentos
Profissional Documentos
Cultura Documentos
In this tutorial, you use the NetBeans IDE to create and deploy a web
application that displays data from a database. The web application
uses the Hibernate framework as the persistence layer for retrieving
and storing plain old Java objects (POJOs) to a relational database.
Hibernate is framework that provides tools for object relational
mapping (ORM). The tutorial demonstrates how to add support for the
Hibernate framework to the IDE and create the necessary Hibernate
files. After creating the Java objects and configuring the application to
use Hibernate, you add Visual Web JSF components to a web page to
display the data.
Before starting this tutorial you may want to familiarize yourself with
using Hibernate.
Hibernate documentation at hibernate.org.
Note. This tutorial uses NetBeans IDE 6.7. If you are using NetBeans
IDE 6.5, please see Using Hibernate in a Web Application in NetBeans
IDE 6.5.
Contents
Query
Adding Additional Helper Methods
Creating the Web Pages
Modifying index.jsp
Creating browse.jsp
Running the Project
6.0.18
Version 5.x
Sakila Database
4. Select the Sakila database from the New Database Name drop
down list in the Create MySQL Database dialog box. Click OK.
When you click OK a Sakila node appears under the MySQL Server
node.
5. Right-click the Sakila node and choose Connect.
When you click Connect a database connection node for the Sakila
database (jdbc:mysql://localhost:3306/sakila [username on
Default]) is listed under the Databases node. When a connection is
open you can view the data in the database by expanding the
connection node.
Creating the Web Application Project
In this exercise you will create a web application project and add the
Hibernate libraries to the project. When you create the project, you will
select Hibernate in the Frameworks panel of the New Project wizard
and specify the database.
1. Choose File > New Project (Ctrl-Shift-N). Select Web Application
from the Java Web category and click Next.
2. Type DVDStore for the project name and set the project location.
3. Deselect the Use Dedicated Folder option, if selected.
For this tutorial there is little reason to copy project libraries to a
dedicated folder because you will not need to share libraries with
other users.
Click Next.
4. Set the server to Apache Tomcat 6.0.18 and set the Java EE
Version to Java EE 5. Click Next.
5. Select the Hibernate 3.2.5 checkbox.
6. Select the sakila database from the Database Connection drop
down list. Click Finish.
When you click Finish, the IDE creates the web application project and
opens the hibernate.cfg.xml file and index.jsp in the editor.
If you expand the Libraries node in the Projects window, you can see
that the IDE added the Hibernate libraries to the project.
management.
If you click the XML tab in the editor you can see the file in XML
view. Your file should look like the following:
<hibernate-configuration>
<session-factory name="session1">
<property
name="hibernate.dialect">org.hibernate.dialect.MySQLDial
ect</property>
<property
name="hibernate.connection.driver_class">com.mysql.jdbc.
Driver</property>
<property
name="hibernate.connection.url">jdbc:mysql://localhost:3
306/sakila</property>
<property
name="hibernate.connection.username">root</property>
<property
name="hibernate.connection.password">######</property>
<property
name="hibernate.show_sql">true</property>
<property
name="hibernate.current_session_context_class">thread</p
roperty>
</session-factory>
</hibernate-configuration>
7. Save your changes to the file.
Creating the HibernateUtil.java Hibernate Helper File
To use Hibernate you need to create a helper class that handles startup
and that accesses Hibernate's SessionFactory to obtain a Session
object. The class callsconfigure() and loads
the hibernate.cfg.xml configuration file and then builds
the SessionFactory to obtain the Session object.
In this section you use the New File wizard to create the helper
class HibernateUtil.java.
1. Right-click the Source Packages node and select New > Other to
open the New File wizard.
2. Select Hibernate from the Categories list and HibernateUtil.java
from the File Types list. Click Next.
3. Type HibernateUtil for the class name and dvdrental for the
package. Click Finish.
and select code generation options (generate code that uses EJB 3
annotations, for example).
Note. The IDE also has wizards to help you create individual POJOs and
mapping files from scratch.
Creating the Hibernate Reverse Engineering File
1. Right-click the Source Packages node in the Projects window and
choose New > Other to open the New File wizard.
2. Select Hibernate Reverse Engineering Wizard in the Hibernate
category. Click Next.
3. Specify hibernate.reveng as the File Name and src/java for the
Folder. Click Next.
4. Select hibernate.cfg.xml from the Configuration File drop down
list, if not selected.
5. Select the following tables from Available Tables and click Add to
add the tables to Selected Tables.
o
actor
category
film
film_actor
film_category
language
Click Finish.
When you click Finish the IDE generates POJOs and Hibernate mapping
files with the fields mapped to the columns specified
in hibernate.reveng.xml. The IDE also adds mapping entries
to hibernate.cfg.xml. You can expand the dvdrental package to see
the files generated by the wizard.
If you click the SQL button you can see the equivalent SQL query.
select film0_.film_id as col_0_0_ from sakila.film
film0_
4. Type the following query to retrieve the records in the Film table
where the film id is between 100 and 200.
from Film as film where film.filmId between 100 and 200
The result window displays a list of records. Now that you have
tested that the query returns the desired results, you can use the
query in the helper class.
5. Add the following method getFilmTitles to FilmHelper.java to
retrieve the films where the film id is between a certain range
specified by the variables startID and endID.
6. public List getFilmTitles(int startID, int endID) {
7.
List<Film> filmList = null;
8.
try {
9.
org.hibernate.Transaction tx =
session.beginTransaction();
10.
Query q = session.createQuery ("from Film as
film where film.filmId between '"+startID+"' and
'"+endID+"'");
11.
filmList = (List<Film>) q.list();
12.
} catch (Exception e) {
13.
e.printStackTrace();
14.
}
15.
return filmList;
}
16.
Add the following method getActorsByID that retrieves the
actors in a particular film. The method constructs the query
using filmId as the input variable.
17. public List getActorsByID(int filmId){
18.
List<Actor> actorList = null;
19.
try {
20.
org.hibernate.Transaction tx =
session.beginTransaction();
21.
Query q = session.createQuery ("from Actor as
actor where actor.actorId in (select
filmActor.actor.actorId from FilmActor as filmActor
where filmActor.film.filmId='" + filmId + "')");
22.
actorList = (List<Actor>) q.list();
23.
24.
} catch (Exception e) {
25.
e.printStackTrace();
26.
}
27.
28.
return actorList;
}
29.
Fix your imports and save your changes.
When you fix your imports you want to
choose java.util.List and org.hibernate.Query.
Adding Additional Helper Methods
You will now add additional helper methods that create queries based
on an input variable. You can check the queries in the HQL query editor.
1. Add the following method to retrieve a list of categories according
to filmId.
2. public Category getCategoryByID(int filmId){
3.
List<Category> categoryList = null;
4.
try {
5.
org.hibernate.Transaction tx =
session.beginTransaction();
6.
Query q = session.createQuery("from Category as
category where category.categoryId in (select
36.
language = (Language) q.uniqueResult();
37.
} catch (Exception e) {
38.
e.printStackTrace();
39.
}
40.
41.
return language.getName();
}
You now have all the classes for your application. Next you will create
the JSP pages and call the helper methods in FilmHelper.java.
Creating the Web Pages
Now that the classes are created, you will create two web pages for
displaying the data. You will modify the index.jsp JSP page so that the
page lists the films in the database. You will also create browse.jsp to
display film details when you click the link on index.jsp.
For this simple example you will add Java code to JSP files, but in
practice you will want to follow the MVC model to remove Java code
from the presentation layer.
Modifying index.jsp
When you created the web application, the IDE automatically generated
the page index.jsp. In this exercise you modify the page to display a
list of film titles. The JSP page calls the getFilmTitles method
in FilmHelper.java to retrieve the film list and then prints a table with
the film title and description.
1. Expand the Web Pages folder in the Projects window and
open index.jsp in the editor.
2. Add the following import tags (in bold) to the JSP page to load the
required Java classes.
3.
4.
<%@page import="dvdrental.*"%>
<%@page import="java.util.List"%>
<%@page contentType="text/html" pageEncoding="UTF-
8"%>
5. Add the following code (in bold) between the body tags to
call FilmHelper.java and retrieve the list of film titles.
6. <body>
7.
<%
8.
9.
int startID = 1;
int endID = 10;
10.
int prev_startID =1;
11.
int prev_endID = 10;
12.
13.
int FILM_RECORD_COUNT = 1000;
14.
15.
boolean RECORD_START_PAGE = false;
16.
boolean RECORD_END_PAGE = false;
17.
18.
if (request.getParameter("startid") != null) {
19.
startID =
Integer.parseInt(request.getParameter("startid"));
20.
}
21.
if (request.getParameter("endid") != null) {
22.
endID =
Integer.parseInt(request.getParameter("endid"));
23.
}
24.
25.
FilmHelper helper = new FilmHelper();
26.
List filmTitles =
helper.getFilmTitles(startID,endID);
27.
28.
if(startID == 1){
29.
RECORD_START_PAGE = true;
30.
}
31.
if(endID == FILM_RECORD_COUNT){
32.
RECORD_END_PAGE = true;
33.
}
34.
35.
prev_startID = startID-10;
36.
prev_endID = endID-10;
37.
38.
startID = endID+1;
39.
endID = endID+10;
40.
41.
int filmTitlesSize = filmTitles.size();
42.
43.
%>
</body>
44.
Add the following (in bold) to generate the table to display
the retrieved items.
45.
int filmTitlesSize = filmTitles.size();
46.
47.
out.print("<table>");
48.
49.
if(RECORD_START_PAGE){
50.
out.print("<tr><td class='NEXT'> </td><td
class='NEXT'> </td><td class='NEXT'> </td><td
class='NEXT'><a class='RENT' href=\"index.jsp?
startid="+startID+"&endid="+endID+"\">Next</a></td></tr>
");
51.
}
52.
else if(RECORD_END_PAGE){
53.
out.print("<tr><td class='NEXT'> </td><td
class='NEXT'> </td><td class='NEXT'><a class='NEXT'
href=\"index.jsp?
startid="+prev_startID+"&endid="+prev_endID+"\">Prev</a>
</td><td class='NEXT'> </td></tr>");
54.
}else{
55.
out.print("<tr><td class='NEXT'> </td><td
class='NEXT'> </td><td class='NEXT'><a class='NEXT'
href=\"index.jsp?
startid="+prev_startID+"&endid="+prev_endID+"\">Prev</a>
</td><td class='NEXT'><a class='NEXT' href=\"index.jsp?
startid="+startID+"&endid="+endID+"\">Next</a></td></tr>
");
56.
}
57.
58.
out.print("<tr><th>Title</th><th>Description</th><th> </
th><th> </th></tr>");
59.
for (int i = 0; i < filmTitlesSize; i++) {
60.
Film film = (Film) filmTitles.get(i);
61.
int filmID = film.getFilmId();
62.
out.print("<tr>");
63.
out.print("<td class='COL1'><a
href=\"browse.jsp?id=" + filmID + "\">" +
film.getTitle() + "</a></td>");
64.
out.print("<td class='COL2'>" +
film.getDescription() + "</td>");
65.
out.print("<td class='COL2'><a
href=\"browse.jsp?id=" + filmID + "\">More</a></td>");
66.
out.print("<td class='COL2'><a href=\"rent.jsp?
id=" + filmID + "\">Rent</a></td>");
67.
out.print("</tr>");
68.
}
69.
out.print("</table>");
70. %>
</body>
71.
Save your changes.
The index page will now display a list of film titles in the database. The
table includes a link to browse.jsp to view details of the film according
to filmId.
Creating browse.jsp
You now need to create the browse.jsp page for browsing details of
the selected film.
1. Right-click DVDStore in the Projects window and choose New >
JSP.
2. Type browse for the JSP File Name.
3. Click Finish.
When you click Finish the file browse.jsp opens in the editor.
4. Add the import tags (in bold) to the JSP page.
5.
6.
<%@page import="dvdrental.*"%>
<%@page import="java.util.List"%>
<%@page contentType="text/html" pageEncoding="UTF-
8"%>
7. Add the following code (in bold) to get the film ID passed
from index.jsp.
8. <body>
9.
<%
10.
//Get title ID
11.
int filmID = 1;
12.
if (request.getParameter("id") != null) {
13.
filmID =
Integer.parseInt(request.getParameter("id"));
14.
}
15.
%>
</body>
16.
Add the following code (in bold) to call the methods
in FilmHelper.java to retrieve the data for the film according to
film ID.
17.
filmID =
Integer.parseInt(request.getParameter("id"));
18.
}
19.
%>
20.
21. <%
22.
boolean startPage = false;
23.
boolean endPage = false;
24.
25.
FilmHelper helper = new FilmHelper();
26.
Film film = helper.getFilmByID(filmID);
27.
28.
String filmTitle = film.getTitle();
29.
String filmDescription = film.getDescription();
30.
31.
//Get Actors
32.
List actors = helper.getActorsByID(filmID);
33.
StringBuffer totalCast = new StringBuffer();
34.
35.
//Get Category
36.
Category category = helper.getCategoryByID(filmID);
37.
String catName = category.getName();
38.
39.
for(int i=0;i<actors.size();i++){
40.
Actor actor = (Actor)actors.get(i);
41.
totalCast.append(actor.getFirstName());
42.
totalCast.append(" ");
43.
totalCast.append(actor.getLastName());
44.
totalCast.append(" ");
45.
}
46.
47.
int langID =
film.getLanguageByLanguageId().getLanguageId().intValue(
);
48.
String language = helper.getLangByID(langID);
49.
int filmLength = film.getLength();
50.
String filmRating = film.getRating();
51.
String filmYear = film.getReleaseYear().toString();
52.
53.
int rentalDuration = (int)
film.getRentalDuration();
54.
float rentalRate =
film.getRentalRate().floatValue();
55.
56.
String specialFeatures = film.getSpecialFeatures();
57.
58. %>
</body>
59.
Add the following code (in bold) to generate the table
displaying the data for the film.
60.
String specialFeatures = film.getSpecialFeatures();
61.
out.print("<table>");
62.
out.print("<tr><td class='RENT'> </td><td
class='RENT'><a class='RENT' href=\"browse.jsp?
id="+filmID+"\">Rent Out</a></td></tr>");
63.
out.print("<tr><td class='TITLE'>Title</td><td
class='TITLE'>" + filmTitle + "</td></tr>");
64.
out.print("<tr><td class='COL1'>Description</td><td
class='COL2'>" + filmDescription + "</td></tr>");
65.
out.print("<tr><td class='COL1'> </td><td
class='COL2'> </td></tr>");
66.
out.print("<tr><td class='COL1'>Genre</td><td
class='COL2'>" + catName + "</td></tr>");
67.
out.print("<tr><td class='COL1'> </td><td
class='COL2'> </td></tr>");
68.
out.print("<tr><td class='COL1'>Cast</td><td
class='COL2'>" + totalCast.toString() + "</td></tr>");
69.
out.print("<tr><td class='COL1'> </td><td
class='COL2'> </td></tr>");
70.
out.print("<tr><td class='COL1'>Movie
Length</td><td class='COL2'>" + filmLength + "
mins</td></tr>");
71.
out.print("<tr><td class='COL1'>Language</td><td
class='COL2'>" + language + "</td></tr>");
72.
out.print("<tr><td class='COL1'>Movie
Rating</td><td class='COL2'>" + filmRating +
"</td></tr>");
73.
out.print("<tr><td class='COL1'>Released On</td><td
class='COL2'>" + filmYear + "</td></tr>");
74.
out.print("<tr><td class='COL1'> </td><td
class='COL2'> </td></tr>");
75.
out.print("<tr><td class='COL1'>Special
Features</td><td class='SPECIAL'>" + specialFeatures +
"</td></tr>");
76.
out.print("<tr><td class='COL1'> </td><td
class='COL2'> </td></tr>");
77.
out.print("<tr><td class='COL1'>Rental Rate</td><td
class='COL2'>" + rentalRate + " US$</td></tr>");
78.
out.print("<tr><td class='COL1'>Rental
Duration</td><td class='COL2'>" + rentalDuration + "
days</td></tr>");
79.
80.
out.print("</table>");
81. %>
</body>
Running the Project
The basics of the application are now complete. You can now run the
application to check if everything is working correctly.
1. Click Run Main Project in the main toolbar or right-click the
DVDStore application in the Projects window and choose Run.
The IDE saves all changed files, builds the application, and
deploys the application to the server. The IDE opens a browser
window to the URLhttp://localhost:8080/DVDStore/ that
displays the list of films.
After testing that the application lists the film titles and displays the
film details, you can add more functions. For example, you can
create rent.jsp to enable the user to rent the title. You can also add
CSS styles to format the pages and add page headers and footers.