Hibernate Made Easy
Simplified Data Persistence with Hibernate & JPA Annotations
Suggested Retail Price:   $54.98
Current Amazon Purchase Price:   $54.98
When you buy through us on Amazon:   $45.98
You won't find a better price!
Buy through us...Help support the site.
Most Popular Videos
'Cuz some people don't like reading...
Hibernate JPA Video CBT Tutorials Setting up the environment  Setting Up Hibernate
Hibernate and RSA IRAD Rational Software Architect Application Developer CBT Tutorial  Hibernate & Rational (IRAD)
Hibernate JPA Training  Many to Many Associations
Java Persistence With Hibernate Tutorials  Inheritance Mapping
Working with Compund Primary Keys  Compound Primary Keys
Hibernate and Eclipse Tools CBT Tutorial  Using Hibernate & Eclipse
Portlet Programming
Do you Portal? Then you need this...
WebSphere: What is WebSphere? Java J2EE JEE Portal and Beyond

I Even Made Portlets Real Easy :)
Please Spread the Word!
Why keep HiberBook a secret???







If you found this site helpful, please tell other people about it. I'd really, really appreciate it.

SCJA Java Study Guide
Written with your success in mind...
WebSphere: What is WebSphere? Java J2EE JEE Portal and Beyond

Get Java Certified by Sun
Is Google Clairvoyant?
Google thinks you'll like this...
What is WebSphere?
I wrote this... I know you'll love it...
WebSphere: What is WebSphere? Java J2EE JEE Portal and Beyond

Buy it now!
Most Popular Purchases
What people are buying from us...
Popular Hibernate Purchases  Hibernate Made Easy
Popular Hibernate JPA Books  Harnessing Hibernate
The Best Spring and Hibernate Books  Java Persistence w Hibernate
Java Persistence API Books  Spring in Action
Popular Spring and JBoss Books  What is WebSphere?
Popular Spring and JBoss Books  JSR168 Portlet Programming
The SCJA Exam Questions
I wrote this, too. A Great Exam Prep...
WebSphere: What is WebSphere? Java J2EE JEE Portal and Beyond

Get Sun Java Certified
Most Popular Tutorials
High hit reads on this site...
Hibernate and JPA Links  How Hibernate Works
Hibernate and JPA Free Tutorials  Recommended Books
Hibernate and JPA Simple Examples  Coding Advanced DAOs
Hibernate and JPA Free CBTs  Using The Criteria API
Hibernate and JPA Simple Examples  What is Hibernate?
down caret hibernate jpaAre you Harnessing It?
One of the three books you need...
Harnessing Hibernate Book by James Elliott (Author), Tim O'Brien (Author), Ryan Fowler (Author)
Read My Review
Win Yourself $100!!!
The 100% Error Free Code Challenge...

The $100 Code Challenge - No Code Errors, Guaranteed!!!
Learn How to Win a Benjamin

HardCore Hibernate
Yeah, you need this book, too...
Hibernate and JPA Simple Examples

If my book makes it Easy, this book makes Hibernate Hardcore. This is the reference standard...You need it.

Read My Review
Friendly Links
Websites we like...
Hibernate and JPA Links  JavaRanch: Big Moose Saloon
Hibernate and JPA Free Tutorials  Apache.org
Hibernate and JPA Free CBTs  Pickering is Springfield
Hibernate and JPA Simple Examples  Hibernate.org
Hibernate and JPA Simple Examples  mysql.org
Hibernate and JPA Simple Examples  Coast to Coast
Hibernate and JPA Simple Examples  What is IBM WebSphere?
Hibernate and JPA Simple Examples  Desktop Tower Defense
Is Amazon Psychic?
Amazon thinks you'll like this...

My Other Books & Stuff
Other decent books of mine :)...
Sun Certified Java Associate SCJA Study Guide  Java Associate Study Guide
SCJA Mock Exam Questions  SCJA Questions Guide
JSR-168 Portlet Development Book  JSR168 Portlet Programming
WebSphere Introduction and Support Book  What is WebSphere?
The Simpsons is based on Pickering Ontario  Pickering is Springfield
Oshawa Ontario, Discerning Bombs A book about like in Oshawa Ontario  Discerning Bombs on Oshawa
A Good Book on Hibernate and JPA the Java Persistence API  Hibernate Made Easy
From Amazon with Love
Check this stuff out...
Please Spread the Word!
Why keep HiberBook a secret???







If you found this site helpful, please tell other people about it. I'd really, really appreciate it.

More Google Stuff...
Links to entertain you...
Most Popular Purchases
What people are buying from us...
Popular Hibernate Purchases  Hibernate Made Easy
Popular Hibernate JPA Books  Harnessing Hibernate
The Best Spring and Hibernate Books  Java Persistence w Hibernate
Java Persistence API Books  Spring in Action
Popular Spring and JBoss Books  What is WebSphere?
Popular Spring and JBoss Books  JSR168 Portlet Programming
Coding Web Based Applications with Hibernate and JPA Annotations
A simple, JSP based example of Hibernate, JPA and the GOF DAO pattern in action...

***NOTE: For some reason, the quotation marks, ", have been deleted from this tutorial. I'm not sure why, but you'll have to use your spidey senses to figure out wher the missing quotation marks should go. Cursed WYSIWYG editors!!!!!

The Web Wizard Using the GenericDAO Pattern, Hibernate and JPA Annotations
(and JSPs Too!!!)

Having worked so hard on our SkillsManager object model, and having put so much effort into creating a data access object design implementation that effectively shields the client application from the back end Hibernate implementation, it would be a shame not to at least create some type of web based, Java application that leverages the facilities of our JPA annotated object model and our data access pattern implementation. So, that's exactly what we're going to do in this tutorial. We're going to create a wizard type application that allows a client to provide their personal information, add addresses, and finally, choose from a list of skills the ones that most accurately reflect their own personal skillset

Simple Development: No Deployment Tutorials

To develop this, I will again use nothing but Java Server Pages. I know, JSF is much sexier, and at the very least, using Servlets as a controller is a much more sound MVC type of architecture, but the thing I'm striving for here is simplicity, and you don't get much simpler than JSPs. And besides, this isn't a book on Servlets, Struts or JSP development. However, I assure you that if you are familiar with Servlets or JSPs, you'll find it extremely simple to take the Java code inside of these JSPs and copy and paste them into your own Servlets or JSF command objects.

Web Application Flow

Before we jump into coding the JSP pages , lets take a look at the basic flow of the web based, SkillsManager web application. The first page will be a very simple form that asks the end user to fill out some personal information.

JSP_with_Hibernate_Login_Form_JPA_Hibernate_Tutorial.gif
The astute observer will notice that the fields in the form above map to fields in both the client and the client_detail tables of the database.

The address.jsp Page

After filling out their personal details and clicking the Next button, the end user will move to the address.jsp page, which asks a user to fill in their address information.

After the end user has filled out all of the fields on the address page, they must click the Add Address button. This will store the address they just submitted and redisplay the address.jsp page, with the address they just entered being redisplayed at the bottom of the page.

JSP_with_Hibernate_Address_Form_JPA_Hibernate_Tutorial.gif

The end user keeps adding addresses until they are satisfied and ready to move on to the skills selection page.

JSP_with_Hibernate_Display_Address_Form_JPA_Hibernate_Simple_Tutorial.gif.

The skills.jsp Page

When the end user clicks on the Continue to Add Skills ++ link, the skills.jsp page will display, showing a list on the left hand side containing all of the possible skills from which the user can select. The end user then selects the skills that are most appropriate and then clicks the Update Skills button. After clicking on this button, the selected skills from the list of skills on the left, appear in the list on the right.

JSP_with_Hibernate_Multiple_Select_List_HTML_Form_JPA_Hibernate_Simple_Tutorial.gif

Summing It All Up!

When the user clicks on the Finish button on the skills.jsp page, all of the data they have input is saved to the database, and a summary is displayed back to the user. It isn't pretty, but it's sufficient for our purposes.

JSP_with_Hibernate_Summary_Page_HTML_Form_JPA_Hibernate_Free_Tutorial.gif

Let's Get Coding!

That should give you a good overview of where I want to take this web based, Hibernate application. With that quick tour of the application, let's start building the first page : the index.jsp.

Adding Client Information : index.jsp

The first page of the SkillsManagerWebApp will simply ask the user for their personal details, namely their firstName, lastName, middleName, emailAddress, username, password and passwordHint.

***NOTE: For some reason, the quotation marks, ", have been deleted from this tutorial. I'm not sure why, but you'll have to use your spidey senses to figure out wher the missing quotation marks should go. Cursed WYSIWYG editors!!!!!
<html><head><title>index</title></head><body>

<form action=address.jsp method=get>
First Name:
<input type=text name=firstName size=30><br/>
Middle Name:
<input type=text name=middleName size=30><br/>
Last Name:
<input type=text name=lastName size=30><br/>
Email Address:
<input type=text name=emailAddress size=30><br/>
Login Name:
<input type=text name=username size=30><br/>
Password:
<input type=text name=password size=30><br/>
Password Hint:
<input type=text name=passwordHint size=30><br/>
<input type=submit name=command value=Next>
</form>

</body></html>
JSP_with_Hibernate_Login_Form_JPA_Hibernate_Tutorial.gif

Furthermore, notice that the action of the JSP page's form is the address.jsp, which will read the information provided through these textfields, and subsequently save the data to the database. Since the address.jsp is going to use some nifty setProperty tags to initialize the needed Client and ClientDetail objects, we must make sure the names of the parameters in the input fields match the names and casing of the corresponding properties defined in the Client and ClientDetail classes.

Note that the name of the submit button is command, and the value associated with someone clicking the button on the Client details page is Next. This will become important in the address.jsp page as it differentiates between requests to add a new client, and requests to add a new address.

The address.jsp Java Server Page

The key visual element to the address.jsp page is the HTML form that allows a user to type in their address information:


<form action=address.jsp method=get>
Address Line 1:
<input type=text name=addressLine1 size=30><br/>
Address Line 2:
<input type=text name=addressLine2 size=30><br/>
City:<input type=text    name=city size=30><br/>
State:<input type=text   name=state size=30><br/>
Country:<input type=text name=country size=30><br/>
Code:<input type=text    name=code size=30><br/>
<input type=submit name=command value=Add Address>
</form>
JSP_with_Hibernate_Address_Form_JPA_Hibernate_Tutorial.gif

Note, that like the index.jsp, the submit button is named command, but the value associated with a user clicking the button to add an address is actually the String "Add Address".

The address.jsp page is very interesting in how it might be invoked. You see, a user can add multiple addresses, so when a user adds an address, the address.jsp page must be designed to handle the submission of the form, store the address data provided by the user, and subsequently redisplay itself so the user can add more addresses. It is not until the users clicks on the link at the bottom of the page that says "Continue to Add Skills" that the user will move away from the address.jsp page and to the skills.jsp page, allowing a user to select the skills that most appropriately match their competencies.

However, the address.jsp page is also invoked when the initial form, asking for all of the Client and ClientDetail data, is submitted. So the address.jsp page must not only handle the submission of address data for the client, it must also be able to handle the submission of all of the Client's basic information as well. Essentially, the kloogyness of the address.jsp page demonstrates why frameworks like JSF and Struts were invented - to help offload the job of controlling application flow to more appropriate command components. Nevertheless, with a little hard work, and a tad of Haitian Voodoo thrown in for good measuer, we can get our address.jsp page to do everything that it needs to do.

Controller Login in the address.jsp

Since the address.jsp can potentially be handing the submission of Client data and the submission of Address data, there needs to be three getProperty and setProperty tags defined for the page, namely tags for the ClientDetail, Client, and Address objects that need to be created and populated based on form data being submitted to the page. Furthermore, since the page will be requiring a number of imports, along with the use of the JSTL core tag libraries, the address.jsp page will need a solid page directive, and a JSTL taglib directive:

***NOTE: For some reason, the quotation marks, ", have been deleted from this tutorial. I'm not sure why, but you'll have to use your spidey senses to figure out wher the missing quotation marks should go. Cursed WYSIWYG editors!!!!!

<%@page 
 import=com.examscam.dao.*,com.examscam.model.*;%>

<%@ taglib prefix=c 
          uri="http://java.sun.com/jsp/jstl/core" %>

<jsp:useBean class=com.examscam.model.Client 
                 id=client scope=session/>
<jsp:useBean class=com.examscam.model.ClientDetail 
                 id=clientDetail scope=request/>
<jsp:useBean class=com.examscam.model.Address 
                 id=address scope=request/>

<jsp:setProperty name="client"       property=* />
<jsp:setProperty name="clientDetail" property=* />	
<jsp:setProperty name="address"      property=* />

Of course, this simply sets up the page for the Java logic that we must implement. Remember, this page can be invoked in one of two ways, either by the clicking of the command button on the index.jsp page, which submits a Client's personal information, or by the clicking of the command button on the address.jsp page. So, an important part of the logic of our address.jsp page is seeing which button, either the one on the index.jsp page or the one on the address.jsp page, triggered the page to be displayed. To figure out which button was pressed, the code looks like this:

String command = request.getParameter(command);

Once we know which command button was clicked, we can implement the appropriate logic.

/* Find out which button was pressed */
String command = request.getParameter(command);

/*This means client information has been submitted */
if ((command!=null) && command.equals("Next")){
/* Perform the logic to add a 
Client and ClientDetail to the database */
}

/* This means the client is adding an address */
if ((command!=null)&& 
               command.equals("Add Address")){
/* Do the logic to add a new Address object 
for the given client to the database*/
}
***NOTE: For some reason, the quotation marks, ", have been deleted from this tutorial. I'm not sure why, but you'll have to use your spidey senses to figure out wher the missing quotation marks should go. Cursed WYSIWYG editors!!!!!

Handling the Submission of Client Info

Of course, with the setProperty tags defined at the top of the JSP page, handling the "Next" command, where a client has submitted their personal details, is fairly easy. All we have to do is grab the already populated Client and ClientDetail objects, make sure they are associated with one another, and then use the DAOs to persist the Client and the ClientDetail instances to the database.

String command = request.getParameter(command);
if ((command!=null) && command.equals("Next")){
  client.setClientDetail(clientDetail);
  clientDetail.setClient(client);
  DAOFactory factory = DAOFactory.getFactory();
  factory.getClientDAO().beginTransaction();
  factory.getClientDetailDAO().save(clientDetail);
  factory.getClientDAO().save(client);
  factory.getClientDAO().commitTransaction();
}

Handling Address Information Submission

Clients can add as many addresses as they like, such as a home address, work address, cottage address, etc. So, when they add addresses, the address information they have submitted gets saved, and the address.jsp page gets redisplayed so they can add more addresses. This creates the scenario where the address.jsp page ends up handing its own form submission.

When someone adds an address, the value of the command button is "Add Address". And of course, the setProperty tags on the page have ensured that an address object has already been populated for us, based on what the user has typed into the various textfields. So, with an address object already created and populated for us, it's just a matter of saving to the database, which with our DAOs, should be easy as 3.14.

if ((command!=null)&& command.equals("Add Address")){
  address.setClient(client);
  client.getAddresses().add(address);
  DAOFactory factory = DAOFactory.getFactory();
  factory.getAddressDAO().beginTransaction();
  factory.getAddressDAO().save(address);
  factory.getClientDAO().save(client);
  factory.getAddressDAO().commitTransaction();
}

One thing you should notice is that the client object is still hanging around, despite that fact that the address.jsp page does not actually contain any html fields that relate to client properties. The existence of the client instance is not magic, though. The Client is still hanging around due to the fact that it was placed in the session scope, as opposed to the request scope:

<jsp:useBean class=com.examscam.model.Client 
                                   id=client scope=session/>

As a result, once the client instance is placed in the session, it will be available to the end user until they either log out, close their browser, or have the server time their session out.

With the client instance available, we can make sure the client and the address objects are associated with each other, and then we can call on the friendly AddressDAO and ClientDAO objects to ensure that our POJOs are properly persisted to the database.

<%@page import=com.examscam.dao.*,
     com.examscam.model.*;%>
<%@ taglib prefix=c 
     uri=http://java.sun.com/jsp/jstl/core %>
<jsp:useBean class=com.examscam.model.Client 
     id=client scope=session/>
<jsp:useBean class=com.examscam.model.ClientDetail 
     id=clientDetail scope=request/>
<jsp:useBean class=com.examscam.model.Address 
     id=address scope=request/>
<jsp:setProperty name=client property=* />
<jsp:setProperty name=clientDetail property=* />	
<jsp:setProperty name=address property=* />
<% 
String command = request.getParameter(command);
if ((command!=null) && command.equals(Next)){
  client.setClientDetail(clientDetail);
  clientDetail.setClient(client);
  DAOFactory factory = DAOFactory.getFactory();
  factory.getClientDAO().beginTransaction();
  
  factory.getClientDetailDAO().save(clientDetail);
  factory.getClientDAO().save(client);
  factory.getClientDAO().commitTransaction();
}
if ((command!=null)&& command.equals(Add Address)){
  address.setClient(client);
  client.getAddresses().add(address);
  DAOFactory factory = DAOFactory.getFactory();
  factory.getAddressDAO().beginTransaction();
  
  factory.getAddressDAO().save(address);
  factory.getClientDAO().save(client);
  factory.getAddressDAO().commitTransaction();
}
%>

<html><head>
<title>address
</title></head><body>
<form action=address.jsp method=get>
Address Line 1:
<input type=text name=addressLine1 size=30><br/>
Address Line 2:
<input type=text name=addressLine2 size=30><br/>
City:<input type=text name=city size=30><br/>
State:<input type=text name=state size=30><br/>
Country:<input type=text name=country size=30><br/>
Code:<input type=text name=code size=30><br/>
<input type=submit name=command value=Add Address>
</form>
<a href=skills.jsp>Continue to Add Skills ++ </a>
</body></html>
***NOTE: For some reason, the quotation marks, ", have been deleted from this tutorial. I'm not sure why, but you'll have to use your spidey senses to figure out wher the missing quotation marks should go. Cursed WYSIWYG editors!!!!!

Displaying a Client's Address Objects

Now, a user can add as many address objects as they like. Obviously, when they come toJSP_with_Hibernate_Display_Address_Form_JPA_Hibernate_Simple_Tutorial.gif the address page for the first time, they haven't added any addresses at all. However, as they do add addresses, we should redisplay them on the page when the address.jsp re-renders. That way, they'll know if the address information they just provided was actually accepted by the server. To do this, we're simply going to add a JSTL for loop to loop through the Client's collection of addresses. Since the Client instance is already stored in the session, and made available to the page through the corresponding getProperty tag, the for:each JSTL custom tag can be implemented by effectively using expression language semantics. Here's how the custom tag would look:

<c:forEach items= var=a>
<hr/>
<c:out value=></c:out><BR/>
<c:out value=></c:out><BR/>
<c:out value=></c:out><BR/>
<c:out value=></c:out><BR/>
<c:out value=></c:out><BR/>
</c:forEach>

Essentially, the items attribute of the forEach tag points to the collection of addresses to which the client is associated. The forEach loop then loops through all of the address instances, using the variable named 'a' to represent the current address in each iteration. Also, notice a little <hr/> tag was used so that each address would be separated by a horizontal rule.

The last thing to pay attention to on the address.jsp page is the anchor tag that allows the user to finish adding addresses, and subsequently jump to the skills.jsp page.

<a href=skills.jsp>Continue to Add Skills ++ </a>
 
<%@page import=com.examscam.dao.*,com.examscam.model.*;%>
<%@ taglib prefix=c 
uri=http://java.sun.com/jsp/jstl/core %>
<jsp:useBean class=com.examscam.model.Client 
  id=client scope=session/>
<jsp:useBean class=com.examscam.model.ClientDetail 
  id=clientDetail scope=request/>
<jsp:useBean class=com.examscam.model.Address 
  id=address scope=request/>
<jsp:setProperty name=client property=* />
<jsp:setProperty name=clientDetail property=* />	
<jsp:setProperty name=address property=* />
<% 
String command = request.getParameter(command);
if ((command!=null) & & command.equals(Next)){
  client.setClientDetail(clientDetail);
  clientDetail.setClient(client);
  DAOFactory factory = DAOFactory.getFactory();
  factory.getClientDAO().beginTransaction();
  factory.getClientDetailDAO().save(clientDetail);
  factory.getClientDAO().save(client);
  factory.getClientDAO().commitTransaction();
}
if ((command!=null)& & command.equals(Add Address)){
  address.setClient(client);
  client.getAddresses().add(address);
  DAOFactory factory = DAOFactory.getFactory();
  factory.getAddressDAO().beginTransaction();
  factory.getAddressDAO().save(address);
  factory.getClientDAO().save(client);
  factory.getAddressDAO().commitTransaction();
}
%>
<html><head>
<title>address
</title></head><body>
<form action=address.jsp method=get>
Address Line 1:<input type=text 
   name=addressLine1 size=30><br/>
Address Line 2:<input type=text 
   name=addressLine2 size=30><br/>
City:<input type=text name=city size=30><br/>
State:<input type=text name=state size=30><br/>
Country:<input type=text 
   name=country size=30><br/>
Code:<input type=text 
   name=code size=30><br/>
<input type=submit name=command value=Add Address>
</form>
<a href=skills.jsp>Continue to Add Skills++</a>
<c:forEach items= var=a>
<hr/>
<c:out value=></c:out><BR/>
<c:out value=></c:out><BR/>
<c:out value=></c:out><BR/>
<c:out value=></c:out><BR/>
<c:out value=></c:out><BR/>
</c:forEach>
<a href=skills.jsp>Continue to Add Skills ++ </a>
</body></html>
 
 
 
***NOTE: For some reason, the quotation marks, ", have been deleted from this tutorial. I'm not sure why, but you'll have to use your spidey senses to figure out wher the missing quotation marks should go. Cursed WYSIWYG editors!!!!!

Adding Skills: The Skills.jsp

The skills.jsp works by displaying a list of all of the available skills in a multi-select list on the left hand side of the page. The end-user then presses the CRTL key and uses their cursor to select multiple skills from the list box. When they have highlighted all of the skills that match their own personal competencies, they click the command button named "Update Skills." The action of this command button is to call the skills.jsp again, and have the page process each skill that was selected in the list of all skills, and subsequently associated those chosen skills with the client.

Of course, the skills.jsp will require the usual suspect of characters, namely the page directive containing the appropriate imports, a taglib directive making the JSTL core custom tag library available to the page, and of course, the requisite jsp:getProperty tag for the client instance that has been stuffed into the session. Furthermore, the page will need the DAOFactory and an initiated transaction if we're going to be hitting the database. The skills.jsp will start off looking like this:

<%@taglib prefix=c 
   uri=http://java.sun.com/jsp/jstl/core%>
<%@page import=com.examscam.dao.*,com.examscam.model.*;%>
<jsp:useBean class=com.examscam.model.Client 
   id=client scope=session/>
	
<%
DAOFactory factory = DAOFactory.getFactory();
factory.getClientDAO().beginTransaction();
### more code to come  ###
%>

Logic of the skills.jsp

The multi-select box that the client chooses skills from is named allskills. So, to find out which skills the user selected from the multi-select box, we simply execute the following piece of code:

String[] clientSkills = 
      request.getParameterValues("allskills");

Again, this code doesn't get all the skills, it simply asks the multi select box that displays all of the skills, which of the skills in the list has the client actually selected. The selected skills are returned in an array of String objects that we call clientSkills.

So long as there are indeed selected skills, we grab the client instance and clear out the old list of client skills, and then, one at a time, we grab the item in the list box that was selected, find the value associated with the selected item, which we will set up to be the primary key of the skill in question, grab that corresponding skill instance from the database using the SkillDAO's findByPrimaryKey method, and then, finally, associate that selected skill with the client. Once we have looped through each of the skills that the client has selected, we can save the client, and rest assured that all of the client's associated skill shave been saved as well.

<%
DAOFactory factory = DAOFactory.getFactory();
factory.getClientDAO().beginTransaction();
String[] clientSkills = 
            request.getParameterValues(allskills);
if(clientSkills!=null) {
  client.getSkills().clear();
  for (int i = 0; i< clientSkills.length; i++) {
    Long id = new Long(clientSkills[i]);
    Skill skill=(Skill)factory.
                  getSkillDAO().findByPrimaryKey(id);
    client.getSkills().add(skill);
  }
  factory.getClientDAO().save(client);
}
%>


***NOTE: For some reason, the quotation marks, ", have been deleted from this tutorial. I'm not sure why, but you'll have to use your spidey senses to figure out wher the missing quotation marks should go. Cursed WYSIWYG editors!!!!!

Displaying all the Available Skills

When the skills.jsp page first displays, all of the skills in the database will be displayed in a multi-select list box. This requires a hardy combination of the HTML select tag, the JSTL forEach custom tag, and a quick interaction with the SkillDAO to retrieve all of the skills in the database. The code for the allSkills multi-select list box is as follows:


<select size=20 name=allskills multiple>

<c:forEach
    items=<%=factory.getSkillDAO().findAll(0,100)%> 
        var=skill >
<option value= id=>
  <c:out value=></c:out>
</option>
</c:forEach>

</select>

As you can see, displaying all of the skills really tests your Java, Hibernate, expression language and JSTL tag library talents.

JSP_with_Hibernate_Multiple_Select_List_HTML_Form_JPA_Hibernate_Simple_Tutorial.gif

Notice that the select box has the name allskills. This is why when we want to know which skills a user has selected, we issue the command:

String[] clientSkills = 
            request.getParameterValues(allskills);

Also notice that for each option element in the select list, that the value that is displayed is the name of the skill, , but the value associated with the option element is actually the primary key of the skill, . Knowing the primary key of the skill the client has selected, we can use the findByPrimaryKey method of the SkillDAO to pull the corresponding Skill instance from the database, and add that skill to the collection of skills that are associated with the client.

Long id = new Long(clientSkills[i]);
Skill skill=(Skill)factory.getSkillDAO().findByPrimaryKey(id);
client.getSkills().add(skill);
***NOTE: For some reason, the quotation marks, ", have been deleted from this tutorial. I'm not sure why, but you'll have to use your spidey senses to figure out wher the missing quotation marks should go. Cursed WYSIWYG editors!!!!!

Displaying the Client's Skills

The code for displaying the client's set of skills is fairly similar to that of the allSkills list, with the exception being the fact that we can simply use the instance of the client that has been pulled out of the session scope to find the skills to display.

<select size=20 name=allskills multiple>
<c:forEach 
   items=<%=client.getSkills()%> var=skill>

<option value= id=>
<c:out value=></c:out>
</option>

</c:forEach>
</select>

Rounding off the HTML form, we need a command button in between the two lists so users can actually commit their selections. All of this must be contained within an HTML <form> tag that points to the skills.jsp page as the value of the action attribute.

<form action=skills.jsp method=post>
<select size=20 name=allskills multiple>
<c:forEach items=<%=factory.getSkillDAO().findAll(0,100)%> var=skill >
<option value= id=><c:out 
  value=></c:out></option>
</c:forEach></select>
<input type=submit name=command value=Update Skills>
<select size=20 name=allskills multiple>
<c:forEach items=<%=client.getSkills()%> var=skill >
<option value= id=><c:out 
  value=></c:out></option>
</c:forEach></select>		
</form>
JSP_with_Hibernate_Multiple_Select_List_HTML_Form_JPA_Hibernate_Simple_Tutorial.gif

Finally, we need a link that takes the user to the final, summary page, of the SkillsManager Web Wizard.

<a href=summary.jsp> Finish  </a>

Ending the Transaction

If you look at the skills.jsp, you'll notice that we kick off a transaction right at the start of the Java logic:

<%
DAOFactory factory = DAOFactory.getFactory();
factory.getClientDAO().beginTransaction();

%>

However, we never actually commit that transaction within that same scriptlet. Strange, isn't it?

Well, actually it's not very strange at all. Not only do we need the transaction to be open within the logic of the scriptlet, but when the select lists are initialized, we're using a SkillDAO to pull all of the skills out of the database, and if the skills of the client are set to lazy-loading, trying to access them outside of the scope of a transaction will create an org.hibernate.LazyInitializationException. To avoid this, we start a transaction right at the beginning of the page, and end that transaction as the page has finished rendering.

</body>
</html>
<%
factory.getClientDAO().commitTransaction();
%>

To finish the skills.jsp page, we need a little scriptlet at the end of the page to finally commit the transaction that we started earlier. Now, one thing that should be mentioned is that since we're using JSPs, we are starting a transaction at the beginning of the page, and committing it at the end of the page. However, it would be more accurate to say that the transaction should be started when the request comes in, and committed when the request has been completely handled, and a response is being sent back to the client. Such an approach is effective, and is commonly referred to as the one transaction per request pattern.

<%@ taglib prefix=c 
  uri=http://java.sun.com/jsp/jstl/core%>
<%@page import=com.examscam.dao.*,
     com.examscam.model.*;%>
<jsp:useBean class=com.examscam.model.Client id=client 
  scope=session></jsp:useBean>	
<%
DAOFactory factory = DAOFactory.getFactory();
factory.getClientDAO().beginTransaction();
String[] clientSkills = 
     request.getParameterValues(allskills);
if(clientSkills!=null) {
  client.getSkills().clear();
    for (int i = 0; i< clientSkills.length; i++) {
      Long id = new Long(clientSkills[i]);
      Skill skill=(Skill)factory
                    .getSkillDAO().findByPrimaryKey(id);
       client.getSkills().add(skill);
    }
  factory.getClientDAO().save(client);
}
%>
<html><head>
<title>skills
</title></head><body>
<form action=skills.jsp method=post>
<select size=20 name=allskills multiple>
<c:forEach items=<%=
      factory.getSkillDAO().findAll(0,100)%> var=skill >
<option value= id=>
<c:out value=></c:out></option>
</c:forEach>
</select>
<input type=submit name=command value=Update Skills>	
<select size=20 name=allskills multiple>
<c:forEach items=<%=client.getSkills()%> var=skill >
<option value= id=>
<c:out value=></c:out></option>
</c:forEach>
</select>		
</form>
<a href=summary.jsp>Finish  </a>
</body></html>
<%
factory.getClientDAO().commitTransaction();
%>
 
 
 
***NOTE: For some reason, the quotation marks, ", have been deleted from this tutorial. I'm not sure why, but you'll have to use your spidey senses to figure out wher the missing quotation marks should go. Cursed WYSIWYG editors!!!!!

The Summary Page: summary.jsp

The summary.jsp page is just that - a simple summary of all of the information that has been saved about the client who has just completed the wizard. The page simply regurgitates all of the information that the client has just provided.

Of course, the page will begin with the standard useBeany tags, taglibs and page directives.


<%@page import=com.examscam.dao.*,com.examscam.model.*;%> 
<%@ taglib prefix=c 
    uri=http://java.sun.com/jsp/jstl/core %>
<jsp:useBean class=com.examscam.model.Client 
    id=client scope=session/>

Of course, there is still a client object floating around in the session. Now, I want to make sure that I have the absolutely most up to date information, so I'll use the id of the client in the session to actually do a lookup directly against the database, using the findByPrimaryKey method of the ClientDAO. Of course, this means going through the DAO factory, and beginning a database transaction as well:

<%
DAOFactory factory = DAOFactory.getFactory(); 
factory.getClientDAO().beginTransaction();
client = (Client)factory.getClientDAO()
          .findByPrimaryKey(client.getId());
%>


And like the skills.jsp before it, the transaction that is started at the beginning of the request is ended as the full JSP page has completed, and content is ready to be delivered to the client:

</body>
</html>
<%factory.getClientDAO().commitTransaction();%>


As far as accessing data, client information is accessed simply using the client instance, and expression language to access the pertinent properties:





 
<%@page import=com.examscam.dao.*,com.examscam.model.*;%> 
<%@ taglib prefix=c uri=http://java.sun.com/jsp/jstl/core %>
<jsp:useBean class=com.examscam.model.Client 
   id=client scope=session/>
<%
DAOFactory factory = DAOFactory.getFactory(); 
factory.getClientDAO().beginTransaction();
client = (Client)factory.getClientDAO()
                  .findByPrimaryKey(client.getId());
%>
<html>
<head><title>summary</title>
</head><body>

<p>Congratulations! You have registered!</p>
<c:out value= /><br/>
<c:out value= /><br/>
<c:out value= /><br/>
<c:out value=/><br/>
<c:out value= /><br/>
<c:out value=/><br/>
<c:out value=/><br/>
<c:out value=/><br/>
<c:out value=/><br/>
<c:out value=/><br/>
<c:out value=/><br/>
<c:out value=/><br/>

<p>Skills:</p>
<c:forEach items=  var=skill >
<c:out value=/><br/>
</c:forEach>

<p>Address Info</p>
<c:forEach items= var=addr>
<c:out value=/><br/>
<c:out value=/><br/>
<c:out value=/><br/>
<c:out value=/><br/>
<c:out value=/><br/><hr/>
</c:forEach>
</body></html>
<%factory.getClientDAO().commitTransaction();%>

***NOTE: For some reason, the quotation
		marks, ", have been deleted from this tutorial. I'm not sure why,
		but you'll have to use your spidey senses to figure out wher the
		missing quotation marks should go. Cursed WYSIWYG editors!!!!!

		

hibernate java hibernate spring hibernate hibernate cache hibernate class hibernate collection hibernate configuration hibernate database hibernate dialect hibernate download hibernate example hibernate mapping hibernate query hibernate sql hibernate tutorial hibernate xml struts hibernate xp hibernate 3 hibernate 3.0 hibernate api hibernate caching hibernate cfg xml hibernate dao hibernate examples hibernate framework hibernate generator hibernate in action hibernate jdbc hibernate list hibernate one to one hibernate plugin hibernate properties hibernate tool hibernate tools hibernate training hibernate tutorials java persistence with hibernate jboss hibernate linux hibernate standby hibernate ubuntu hibernate xdoclet hibernate hibernate synchronizer computer hibernate disable hibernate enable hibernate hibernate 2 hibernate 3.2 hibernate annotation hibernate annotations hibernate bag hibernate batch hibernate blob hibernate button hibernate c3p0 hibernate cascade hibernate command hibernate composite id hibernate composite key hibernate config hibernate connection hibernate criteria hibernate date hibernate delete hibernate discriminator hibernate documentation hibernate ehcache hibernate entitymanager hibernate enum hibernate fetch hibernate file hibernate filter hibernate flush hibernate formula hibernate forum hibernate hbm hibernate hbm2ddl hibernate hbm2ddl auto hibernate hql hibernate id hibernate in vista hibernate inheritance hibernate insert hibernate interceptor hibernate interview questions hibernate inverse hibernate javadoc hibernate join hibernate jpa hibernate lazy hibernate lazy loading hibernate load hibernate logging hibernate many to many hibernate many to one hibernate map hibernate mapping file hibernate merge hibernate mode hibernate named query hibernate order hibernate order by hibernate org hibernate performance hibernate problems hibernate property hibernate proxy hibernate query language hibernate reference hibernate restrictions hibernate reverse engineering hibernate save hibernate saveorupdate hibernate search hibernate select hibernate sequence hibernate session hibernate sessionfactory hibernate set hibernate shortcut hibernate show_sql hibernate source hibernate sql query hibernate stored procedure hibernate template hibernate timestamp hibernate transaction hibernate type hibernate update hibernate usertype hibernate validator hibernate version how to hibernate laptop hibernate net sf hibernate netbeans hibernate org hibernate dialect org hibernate session sleep hibernate sleep vs hibernate spring and hibernate standby vs hibernate turn off hibernate vista hibernate what is hibernate windows hibernate windows xp hibernate all 150 Help java spring apache xml ajax cache cmp j2ee s truts tomcat ejb jboss jsf maven primary key ruby on rails foreign key hibernation ibatis one to one spring framework xdoclet hql hybernate jdo many to many middlegen ojb one to many

eXTReMe Tracker