Thursday, March 31, 2011

Technologies and versions

.

Technologies Versions

.

20032004200520062007200820092010

.

Agile--------

.

AjaxN/AN/AN/A-----

.

Design Pattern--------

.

EJB2.12.12.13333.13.1

.

Hibernate

.

HTML4.0.14.0.14.0.14.0.14.0.1

.

J2EE1.3 / 1.41.41.455556

.

Java Script1.51.51.61.71.71.81.8.21.9

.

JDBC33

.

JDK1.3/1.41.51.51.5/1.61.61.61.61.6

.

JMS1.11.11.11.11.11.11.11.1

.

Jquery----1.0.1/1.0.2/1.0.41.1 / 1.21.2 / 1.2.1---1.2.6 / 1.3 1.4

.

JSF-1.0 / 1.11.0 / 1.11.1 / 1.21.21.222

.

JSM

.

JSP1.21.222222.12.1

.

Oracle Server8i8i / 9i9i9i/10g10g10g /11g10g / 11g11g / 11i

.

Perl Script [1]5.85.85.85.85.85.85.85.8

.

PHP [2]4.3.04.3.0 / 5.04.4.0 / 5.1.04.4.04.4.0/ 5.24.4.85.2.115.2.12

.

Servelet2.2/2.32.2/2.32.2/2.32.32.32.3/2.4/2.52.53

.

Spring 3.0.3

.

Spring MVC

.

SQL server

.

Struts

.

Web Services

.

XML

.

Websphere Application Server [3]4.0/5.05.0/5.1/6.05.0/5.1/6.05.0/5.1/6.15.1/6.15.1/6.1/7.06.1/7.08.0 Beta

.

Eclipse-33.1Callisto 3.2Europa 3.3Ganymede 3.4Galileo 3.5Helios 3.6

.


Wednesday, March 30, 2011

Arrays: Copy vs. Clone

Occasionally when working with an array is may be useful to make a copy of that array. What might not be apparent is that by making a copy of an an array there are implications that can cause unintended side-effects if one isn’t aware of what actually happens when a simple copy the array is made.

For instance let’s consider:

int [] numbers = { 2, 3, 4, 5};

int [] numbersCopy = numbers;

The “numbersCopy” array now contains the same values, but more importantly the array object itself points to the same object reference as the “numbers” array.

So if I were to do something like:

numbersCopy[2] = 0;

What would be the output for the following statements?

System.out.println(numbers[2]);

System.out.println(numbersCopy[2]);

Considering both arrays point to the same reference we would get:

0

0

for an output.

But what if we want to make a distinct copy of the first array with its own reference? Well in that case we would want to clone the array. In doing so each array will now have its own object reference. Let’s see how that will work.

int [] numbers = { 2, 3, 4, 5};

int [] numbersClone = (int[])numbers.clone();

The “numbersClone” array now contains the same values, but in this case the array object itself points a different reference than the “numbers” array.

So if I were to do something like:

numbersClone[2] = 0;

What would be the output now for the following statements?

System.out.println(numbers[2]);

System.out.println(numbersClone[2]);

You guessed it:

4

0

Friday, March 25, 2011

Introduction To JSTL




Introduction

As J2EE programmers, we are familiar with Servlets , JSP and JavaBeans. Any JSP page should encapsulate the business logic in a bean and invoke it by using tag. Till recently, a combination of Servlets, JSP and beans was the standard practice. But, the JCP realeased an API for enabling programmers to create custom tags and use them in their JSP pages. The difference between javabean and java custom tags was that, though both made use of java classes, tags can be used by non-programmers also without knowledge of Java programming, just as they would use html tags.( From a programmer's perspective,however, a much more important distinction is that tags are specific to the page in which they are created while javabeans are general. )

{{{ Back in 1998, a Web-Server Technology , known as ColdFusion , created by Allaire of Allaire Corporation, was very much in demand!. It was a purely tag- based language, using which page-authors can turn into programmers overnight. The tags were so powerful and simple to use! There is a separate lesson on using ColdFusion for typical web-based database opeartions, elsewhere in this edition, just to indicate the source of inspiration of the tag library idea, of the JSTL. To this day, ColdFusion is unbeatable, in its power,speed, ease of use and productivity. However, among the various web-server technologies ( namely ASP, Servlets, JSP,Perl,PHP , ColdFusion & ASP.net), CF is the only technology that is not free!And perhaps for this reason, it is no longer popular in Indian environment, though it is said to be very much in vogue still, in US!

MacroMedia of 'Flash fame' purchased ColdFusion. There was even a tutorial on MacroMedia ColdFusion Exprsess in DeveloperIQ., a few months back.It is interesting to make a comparison of the CF tags approach and the JSTL approach., especially , in DataBase operations.Readers are requested to read the lesson on ColdFusion,in this edition, after covering sql tags in JSTL , in the fourth part of this tutorial.. }}}

To resume,the release of the TagLibrary API, triggered a lot of activity and hundreds of tags were introduced by the java community, some of them 'open' and a few 'proprietary'. This led to a lot of confusion in code maintenance, because knowledge of Java was no longer sufficient to understand and interpret a given jsp page using non- standard tags .The JCP had unwittingly introduced elements of confusion by the JSP-Custom-Tag specification.

To correct this problem, Sun and JCP, initiated the JSP-Standard Tag Library (JSTL) project. Though there are a number of popular and powerful tag-libraries, it is always better for j2ee coders to adopt the JCP standard because, it is likely to be merged into the core specification of Java langauage itself , in future. (That yardstick may be valid for all creations, in Java world. Splintering of the Java platform due to' hyper-active creativity' without the corresponding discipline to get it through a standards body ,is the greatest threat, looming large in the Java-horizon.

Too frequent revisions and additions, that too without caring for backward compatibility,are not conducive to programmer productivity and the net result is that programmers spend ,in learning new twists in grammar, their precious time which should have been spent more usefully in applying that grammar in solving business-logic problems and acquiring proficiency in the chosen application-domain. While, tag library is sometimes very elegant and simple to use, it defeats the very purpose if the tags are not standard tags and if there is proliferation of non-standard tags. It is for this reason that JSTL merits our serious study and adoption.

JSTL is a quite recent development. It was only in 2003, that the official version 1.1 was released and now incorporated into JSP-2.

According to the latest position, the JCP is suggesting that a JSP page should be completely free from any trace of Java code! So, programmers who were writing their JSP using Javabeans and scriptlets , may not be able to carry on in their old style as, to prevent programmers from introducing scripting sections in their pages, there is a provision for turning off scriptlets altogether from a jsp page. If that happens ,all our knowledge of Java coding will be of little use in creating a jsp page, though such knowledge may be useful in creating beans and other types of java programs.

It is thus very important for J2EE students, to understand the trend and get to know the techniques, advantages and limitations of tag libraries...In a way, a study of JSTL is almost synonymous with a study of the latest version of JSP (ie) JSP2.0 .

Getting Started

Without an introductory demo for each of these types, it may be difficult to appreciate the significance of the above lines. So we will now give simplest illustration.

[It is presumed that readers are conversant with basic Servlets & JSP techniques and executing them in Tomcat environment.]

Servlets are full-fledged java-classes and so are very powerful. But, when we want to create a dynamically-generated web-page using servlets, it becomes difficult and clumsy. Let us consider a very simple example.

The user fills up text in html form with his name and submits the form,to the servlet. The servlet reads the data , appends a greeting and sends it back to the user.

We being with a simple html form:

greeting.html   

Relevant section of Greeting.java servlet

Greeting.java ( code-snippet only)  public void doPost(HttpServletRequest req, HttpServletResponse  resp)     throws  ServletException,IOException {      resp.setContentType("text/html");     PrintWriter  out = resp.getWriter();     //-------------------------------     String  s = req.getParameter("text1");     out.println("");     out.println("We  welcome"+",
"); out.println (s); out.println(" "); }

It will be noticed that we have to write so many 'out.println' statements. This makes the page unreadable.( If String-buffer is used , we can do it with just a single out.println , but forming the correct string may pose difficulties).

It is to solve this problem that JSP was developed(1999). While a servletinterposes HTML in java code, JSP interposes java-code in HTML, as some authors correctly observe..( in this case, we have to modify the action field in html form, so that it refers to the following greeting1.jsp).

Delimeters

Student readers will know about 'delimiters' ( <%) in ASP. This is the same as in JSP. Only the syntax is slightly different. In JSP parlance, the code within delimiters is known as 'scriptlet'.( see greeting1.jsp)

greeting1.jsp    <%     String   s = request.getParameter("text1");     out.println("we welcome"+
); out.println(s); %>
Expressions

Some coders prefer to use expressions.

What is an 'expression'? It is a method of sustituting request-time values in html page. ( see greeting2.jsp). Carefully note that there is no semi-colon after ("text1").

greeting2.jsp         We welcome
<%= request.getParameter("text1") %>
Using a java bean

The third variant is to use a javabean to encapsulate the business-logic. We develop a jsp-bean as follows:

greeter.java  package ourbeans;  public class  greeter {     public greeter()  {  }     public  String   greetme(String s) {         return  "we welcome..."+s;     } }

This source file is compiled and the class-file is copied to :

'e:\tomcat5\webapps\root\WEB-INF\classes\ourbeans'

(Carefully note that WEB-INF folder name should be in capital letters).

(Anytime, a new class is placed in Tomcat, we should remember to restart the server).

We can now write our JSP code as follows:
greeting3.jsp     <%     String  s = request.getParameter ("text1");     String  r =     bean1.greeteme(s);     out.println(r); %>  
Enter JSTL

We are now entering JSTL zone. How exactly we should proceed to install JSTL, we will take up shortly. For the moment, we are just getting familiar with the required syntax. We begin with taglib directive:

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

The directive says that we are using 'core' tags and the prefix will be 'c'. If we want to assign the value 'sam' to a variable 'a' and then print it, the JSTL code will be:

 

The Dollar sign & brace will be familiar ground for Perl programmers. In JSTL & JSP-2, it is known as EL ( Expression Language).

To consider another example, In a servlet & jsp, we write:

String s = request.getParameter("text1");

to collect the input from the user.

The same job is done in JSTL by:

With these brief hints, it should not be difficult to understand the following JSP page written by using JSTL core-tags.

greeting4.jsp (uses  JSTL)  <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core"%>            We welcome

In the previous examples, there was java code in a few lines at least. But, in the JSTL example, we find that there are only tags and no java scriptlets. This is the avowed objective of the JSTL initiative under the auspices of Java Community Project! Why? This enables, clean separation of Page author's role and Logic programmers' role. Thus maintenance becomes easy.

Getting Set Up

There are five groups under which the JSTL tags have been organized.

They are as follows:

  1. core
  2. xml
  3. sql
  4. formatting
  5. functions

The most difficult part is to set up Tomcat so that it executes JSTL. There are some basic requirements, before we can experiment and study the use of JSTL.All that we have studied in using Tomcat for servlets and JSP may not be sufficient to learn JSTL, because, jstl library is not built into Tomcat5 even, as yet.

Without hands-on experimention, JSTL could be confusing and strange, because of the fact that it is very recent . But in coming months, support will be built into Tomcat and we won't have to worry about installing the JSTL libraries inside Tomcat. But, as it is, we have to learn how to set up the necessary development environment..

So, how do we go about , placing the JSTL libraries in tomcat?

The best solution is to get JWSDP1.3. This is Java Web Service Development' Pack. (Carefully note the version , however!).

It is good to start with this because, it contains a lot of valuable software , including the latest and greatest from JCP, (ie) JSF (Java Server Faces).... which may soon replace Struts.

We unzip the jwsdp1.3 and install it in C: drive.

There are a number of folders like JAXP, JAXR, JAXB,JAX-RPC, JSF, JSTL etc. in the JWSDP pack.

For the present, we are interested in JSTL folder only. If we expand the JSTL folder, we find four sub folders:

a) docs
b) lib
c) samples
d) tld (tag library descriptors)

When we look into the 'lib' folder, we find two jar files:

a) standard.jar
b) jstl.jar

We should copy these two jar files into :

'e:\tomcat5\webapps\root\WEB-INF\lib'

(Remember to restart the Tomcat server).

That is all that is required to use JSTL!

The included taglibrary descriptors do not have to be placed in the WEB-INF folder.These files are already included in the /META-INF folder of the jstl.jar and so will be automatically loaded by Tomcat, when it is restarted.

(We are using tomcat5 & jdk1.4.2. The results are not ensured for other environments. However, we adopted the same method in Tomcat4.1 with jdk1.41 and got correct functioning.)

The JSTL folder contains a sub-folder named 'tld'. There will be a number of tld files there such as

c.tld, ( core)
x.tld, (xml)
fmt.tld, (format)
sql.tld & (sql)
fn.tld. (functions)

Some authors say that we should copy these tld files to ... :\tomcat5\webapps\root\WEB-INF folder. A few others , say that there is automatic detection and so it is not necessary. We chose not to copy the tld files into e:\tomcat5\webapps\root\WEB-INF folder ! We found that the programs work well. No problem!

When we study the web.xml file in e:\tomcat\webapps\root\WEB-INF folder, we find that it follows DTD and not Schema. ( DTD stands for Document -Type- Definition). ( Schema serves the same purpose but is in XML format and is more powerful. The default is DTD ).

This point is very important. The default allows us to use EL,(Expression Language) but by using

If we modify the DTD into the prescribed J2EE schema , we can directly print as ${s}. This requires very careful handling and we take it up later.

For the present , let us not tamper with the DTD. or the web.xml file.

In the next part of this tutorial, we study the tags available in the JSTL-core library.

CORE TAGS IN JSTL

[ In the second part of this tutorial on JSTL, the author explains how the tags in the core-group can be used in JSP pages, with a number of simple examples.]

We are now ready to experiment with all the tags in the core library. The core tags have the following uniform uri:

http://java.sun.com/jstl/core

(In the book by Hans Bergsten titled,"Java Server Pages" ( third edition), (OReilly pub)the uri is consistently given as : 'http://java.sun.com/jsp/jstl/core'.It looks as if there has been some change in specification and grammar, after it was published. This appears to be wrong as the server threw exception. The correct uri is : 'http://java.sun.com/jstl/core'.)

The prefix is ‘c:’

The following tags are available in the ‘core’ library. ( Remember them as a dozen!).

We will now see simplest illustrations for the above tags.There are a dozen demos, to bring out the features of each of these tags.


Example 1

demo1.jsp uses We create demo1.jsp as: e:\tomcat5\webapps\root\demo1.jsp

demo1.jsp  <%@ page contentType="text/html" %> <%@ taglib prefix="c"  uri="http://java.sun.com/jstl/core"  %>       
NAME
PLACE
NAME:
PLACE:

In all the previous examples, we invoked the JSP file through a html file. But, in demo1.jsp, we are posting the page to itself.( in asp.net style!).( but there is no 'retention of data' , unlike asp.net).

We start Tomcat5, and type the url as: ‘http://localhost:8080/demo1.jsp’. in the browser.

We get a form with two text boxes and a submit button. We fill up the textboxes with name and place and submit.The demo1.jsp executes and displays the values entered by the user.due to the JSTL tags: etc.

Example 2

The second example is very important. When the user enters data in a number of fields, it is tedious to collect the data and transfer it to jsp page for processing. In our example, we are collecting data about a player, such as his name, place and game. We can have much more but we are restricting for space considerations. JSP has an action tag , known as 'jsp:setProperty'. Using this along with a standard javabean, we can extract data and transfer it to our program in a single step.

The syntax is

        

( the * sign denotes 'all').

But, we should first create the 'player ' bean with all the attributes and getter & setter methods, as shown:

player.java  package ourbeans;  public class Player {     private String name;     private String place;     private String game;      public String getName() {         return name;     }     public void setName(String name) {         this.name = name;     }     public String getPlace() {         return place;     }     public void setPlace(String place) {         this.place = place;     }     public String getGame() {         return game;     }     public void setGame(String game) {         this.game = game;     } }

In demo2.jsp, we collect the data and then display the data entered by the user. Note that instead of {param.text1}, we are using {bean1.name}. We should carefully name the html form controls with the corresponding attribute names given in the bean. We cannot name the controls as 'text1' etc, now!




demo2.jsp  <%@ page contentType="text/html"%> <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core"%>    
Name
Place
Game
Name:
Place:
Game:

Once again, it will be noticed that there is no java code in this example, as everything is being done by tags, only.


Example 3 - Condition Tags

We are now ready to take up examples for 'condition' tags. There are two types of 'condition tags': namely, & .

In the third demo, we learn how to use the

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

There is a combo with two options, namely 'sam' and 'tom'. If the user selects 'sam' and submits the form, he gets 'GoodMorning ...SAM!". If he selects 'tom' instead, he gets 'How are you..TOM?'.

The above code is no ‘Rocket-Science’ as American authors say!But , if we are careless in typing the names ‘sam’ or ‘tom’ in the test condition, we could spend hours together , trying to coax this code into functioning! We should not leave space after the single quote in the 'test expression'. Second point worth noting in the above example is that we can use either == ( double equal to) or eq to test equality.


Example 4 - c:choose

The syntax is:

              something                   something       
The peculiarity to be noted here is that unlike <demo4.jsp <%@ page contentType="text/html" %> <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
Today is
Sunday Monday Tuesday Wednesday Thursday select between 1 & 5

When we choose '7', "select between 1 & 5 " will be displayed!


Example 5 - Iteration c:forEach

We are familiar with the 'for-each' construct. JSTL's 'for-each' also has the same functionality. In the following example, we have a String array. named as 'colors'. By using the tag, we iterate through the array and display the values.

demo5.jsp  <%@ page contentType="text/html" %> <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %> <% pageContext.setAttribute("colors", new String[] {"red","green","blue","orange","black"} ); %>      

We get the following display, when we execute the program.

0

1

true

false

red

1

2

false

false

green

2

3

false

false

blue

3

4

false

false

purple

4

5

false

true

black

action tag contain the following attribute list:

items       :  the collection of items like String[] var         :  a symbolic name for the collection begin       :  the starting index of iteration end         :  the ending index of iteration step        :  incremental step varStatus   :  symbolic name for current status.

If we assign the symbolic name 'a' for the status, we are able to access its properties such as index, count, whether it is first item, whether it is last item and the current value.


Example 6 - c:forEach cont.

Demo6 also deals with iteration tag. In the following example, the iteration starts at value 3 and ends at value 8. It displays the values of n in each iteration. Each iteration increments the value of n automatically by 1, if step is not specified.

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

Resulting html display for demo6.jsp: 3,4,5,6,7,8


Example 7 - c:forTokens

Demo7 deals with JSTL's 'forTokens' tag., which iterates over a string of tokens separated by a set of delimiters like the stringTokenizer class in Java.

demo7.jsp
<%@ page contentType="text/html" %> <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>             
Name Place Degree Age Mark

Resulting HTML displayed:

 NAME    PLACE   DEGREE   AGE     MARK SAM     DELPHI  MCA      24      90 

The essential attributes of 'forTokens' tag are:

Items: String to tokenize
Delims: The delimiter characters that separate the tokens of the string.


Example 8 - c:import

Demo8 deals with URL-Related actions. action tag imports the conent of a URL-based resource and provides a simple way to access URL-based resources that can either be included or processed within the JSP.

In the following example,the import action tag imports the content of welcome.htm file here.So it displays the contents of demo8.jsp and welcome.htm.

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

Example 9 - c:url

In demo9 we discuss the action tag.

prints the value of URL. It is easier to construct the hyperlinks. It is useful for session preservation (URL-Encoding).

In the following example,we use to make a link to another html file. When we execute demo9, we get a link , with text 'send'. When we click on the link, we are taken to welcome.htm.

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

Example 10 - c:redirect

demo10 deals with action tag.

This tag forwards the browser to the specified URL.

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

Example 11 - c:param

Finally, tag is useful to send some parameter value to the page to which redirect occurs. In our example, the code redirects to sample.jsp, but it takes the param named 'a' with value='SAM', to the redirected page.

And, the sample.jsp accepts this param and prints it.
 demo11.jsp  <%@ page contentType="text/html" %> <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core"  %>    
( in a different file )
sample.jsp  <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %> 

And to end our whirlwind tour of core-tags in JSTL, here is a demo which mixes EL of JSP-2(Expression Language of JSTL) with 'Expression' (also known as request-time Expression ) of JSP1.2.

demo12.jsp  <%@ page contentType="text/html" %> <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core"  %> JSTL  welcomes 

JSP Expression welcomes <%=request.getParameter("text1") %>

In the next and third part of this tutorial, we will learn about xml tags in JSTL.

JSTL & XML-TAGS

In this third part of the tutorial on JSTL, the author explains the use of xml tags of the JSTL and shows their wonderful simplicity ,ease of use and raw power.

No one can have any second opinion about the elegance of xml tags in JSTL. If the readers have been following the earlier installments of this J2EE series of tutorials, they would have come across JAXP,DOM,SAX ,JDOM and such terms, and it may have been none too easy to learn. But the xml tags in JSTL , make XML processing and even Transformation , a cinch! And ,we now proceed to study them.

Making our study even easier, many of the xml tags in JSTL , are very much similar to the 'core' tags. For example, just like , we have .

Similarly, , , etc.

So, if we have understood the syntax of the 'core'; tags, it will not be difficult to use the 'xml' tags.

All the following examples use the books.xml file.It contains 'elements' like 'title' and 'author':

 books.xml                  cobol          roy                    java          herbert                    c++          robert                    coldfusion          allaire                    xml unleashed          morrison                    jrun          allaire       

XML Demos

The following program reads the xml file using 'forEach' tag and displays the title and author of each book..

The syntax: is used to select the elements from the xml file. is used to print the elements of the xml file. We begin by importing the reference to the XML file to be parsed.

We have given a symbolic name for this file as 'url'.Next we ask the program to parse this XML file.The resulting tree is given a symbolic name as 'doc'.

In the next step, we direct the program to select each title and each author in the XPATH expression $doc/books/book. If we refer to the xml file , we find that the root element of the document is 'books'. Inside this, we have 'book'.So, XPATH can be thought of as just a file hierarchy. Just like

demo1.jsp  <%@ page contentType="text/html" %> <%@ taglib  prefix="c" uri="http://java.sun.com/jstl/core" %> <%@ taglib  prefix="c" >uri="http://java.sun.com/jstl/xml" %>        -----------------------------------------------


========

Magically, we have parsed a given XML document and extracted information, without any mention about DOM,SAX and such words., atall!Wonderful!As a famous author would say, 'anything that makes my job easier, I like!'. When we execute the 'program', we get the following result.

(Result for executing demo1.jsp)

========================== cobol roy ========== java herbert ========== c++ robert ========== coldfusion allaire ========== xmlunleashed morrison ========== jrun allaire ==========

The following program (demo2)displays the books and authors of xml file in table format.

demo2.jsp  <%@ page contentType="text/html" %> <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %> <%@ taglib prefix="c" >uri="http://java.sun.com/jstl/xml" %>              
tr> title author

Results of Demo 2:

 title           author -----           ------ cobol           roy java            herbert c++             robert coldfusion      allaire xml unleashed   morrison jrun            allaire 

demo3 deals with the selection of particular book's author from the xml file ,when we give the title, with the help of action tag.The title is choosen from combo box in demo2.htm file and submitted.We get a display of the selected title and its author. Think of this as an sql query like "select * from table1 where title='jrun'"

demo3.htm     SELECT THE TITLE.
YOU WILL GET TITLE & AUTHOR.
demo3.jsp  <%@ page contentType="text/html" %> <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %> <%@ taglib prefix="c" uri="http://java.sun.com/jstl/xml" %>         ------                        

demo4 is a simple variation on the same theme. In this case, the user selects the author name from the combo and any books by that author are displayed, due to the code. It will be noted that 'allaire' has two books to his credit and so if we choose 'allaire' in the combo,his two books are displayed.If 'haris' is chosen, we should display the message that it is yet to be published as there is no such entry in the xml file. But there is no 'if-else' construct and so we improvise. We have created a variable 'a' and assigned the value 'ok' to it. If there is no author to match the user's selection, the conditional block is ignored and 'a' will not be 'ok'. From this, we conclude that 'the book is not ready'.

demo4.htm    Select name of author & view his books
demo4.jsp  <%@ page contentType="text/html" %> <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %> <%@ taglib prefix="c" uri="http://java.sun.com/jstl/xml" %>                                                                   

In demo5 also, we display the title & author for a given title, but we now use

demo5.htm    SELECT THE TITLE.
YOU WILL GET TITLE & AUTHOR.
demo5.jsp  <%@ page contentType="text/html" %> <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %> <%@ taglib prefix="c" uri="http://java.sun.com/jstl/xml" %>                                                                                        
Result ====== -------------------- title: c++ -------------------- c++ robert ========================- title: VB -------------------- no such book

In demo6 , we see XSLtransform using JSTL. We'll be using students.xml and xsl1.xsl as shown below the demo. Just three lines and DONE!

 Demo 6  <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %> <%@ taglib prefix="x" uri="http://java.sun.com/jstl/xml" %>        
// students.xml                Thomas         Delhi         1111         78                   David         Bombay         4444         90                   Mathew         Bangalore         5555         92                   John         Hyderabad         6666         72      
//xsl1.xsl                                       
Name Place Number Mark

Name

Place

Number

Mark

Thomas

Delhi

1111

78

David

Bombay

4444

90

Mathew

Bangalore

5555

92

John

Hyderabad

6666

72

That completes our study of 'xml' tags in JSTL.We now move ahead to the fourth and final part of the present tutorial, dealing with 'sql' tags in JSTL.

Part 4 - JSTL SQL Tags

In this fourth & last part of the tutorial on JSTL,the author deals with the 'sql' tags in JSTL and shows how they greatly simplify simple database operations like 'select' queries. In another demo, common database operations like 'add','modify' , 'delete' & 'verify'also are dealt with.

The Struts community has ordained that JSP should be strictly a 'view-technology', in the Model-View-Controller Architecture. According to Struts philosophy, JSP should not deal with Data-Accesss and such data access should be done by 'Model' components only.( read 'beans'). JSTL , however, provides for sql tags, inspired by ColdFusion! And , a few months back, the editor of 'Java Lobby' magazine was all admiration for the absolutely nice features of these sql tags, whatever, 'struts-fans' may say! Just as EJB may be 'overkill', except for really big Enterprise applications, Struts also may be an unnecessary complication for small and medium level projects. In such cases, it is much more direct to provide for data access by the JSP itself, but using JSTL 'sql' tags.We take up these 'sql' tags in this part of the tutorial.

Let us begin with 'sql.htm'. It just provides a simple form with just a textarea & submit button. Normally, queries by MIS department will be very complex and so we have provided a textarea for the 'select' query.After filling up the query, it is submitted and the corresponding query.jsp is invoked.

query.htm    

query.jsp is given below. In the standard jdbc code,we begin by asking for the availability of the driver. "jdbc.odbc.JdbcOdbcDriver". And then, we specify the URL of the database as 'jdbc:odbc:telephone'.

-

Similarly, in JSTL also, we begin with

The next step is to collect the query typed in area1 by the user. is used for this purpose.We also check up whether the query typed by the user has indeed been correctly received using

Next, the '

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

In the second example,(dbeditor.htm & dbeditor.jsp) we provide a combo, with options such as: add, modify, remove and verify. In JSTL , we have a separate sql tag known as '

dbeditor.htm        
name
number
criterion

dbeditor.jsp  <%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %> <%@ taglib prefix="c" uri="http://java.sun.com/jstl/sql" %>                                                           <--sql should be typed in a single line -->                                                            
Conclusion

These are , afterall, the essentials. All else, are only, ornamental. Thus, it will be seen that the JCP has done a great job in creating really fine standard tags, for simplifying routine tasks. But, Java coders, have to take note that , their job as JSP coders, will be slowly eroded by page-authors using JSTL!

Suggested Reeference Books

  1. Pro JSP by SIMON BROWN & OTHERS (A-Press) (Excellent material)
  2. JavaServer Pages by Hans Bergsten ( Third Edition) (O'Reilly Press/SPD)
  3. EARLY ADOPTER JSP Standard Tag Library by JAYSON FALKNER & OTHERS Wrox Press
  4. JSTL in Action by SHAWN BAYERN (Manning/ DreamTech).
http://www.learntechnology.net/content/jstl/jstl_intro.jsp

Thursday, March 24, 2011

Best practices to improve performance in JDBC

    This topic illustrates the best practices to improve performance in JDBC with the following sections:

    Overview of JDBC

    JDBC defines how a Java program can communicate with a database. This section focuses mainly on JDBC 2.0 API. JDBC API provides two packages they are java.sql and javax.sql . By using JDBC API, you can connect virtually any database, send SQL queries to the database and process the results.

    JDBC architecture defines different layers to work with any database and java, they are JDBC API interfaces and classes which are at top most layer( to work with java ), a driver which is at middle layer (implements the JDBC API interfaces that maps java to database specific language) and a database which is at the bottom (to store physical data). The following figure illustrates the JDBC architecture.

    JDBC API provides interfaces and classes to work with databases. Connection interface encapsulates database connection functionality, Statement interface encapsulates SQL query representation and execution functionality and ResultSet interface encapsulates retrieving data which comes from execution of SQL query using Statement.

    The following are the basic steps to write a JDBC program

    1. Import java.sql and javax.sql packages

    2. Load JDBC driver

    3. Establish connection to the database using Connection interface

    4. Create a Statement by passing SQL query

    5. Execute the Statement

    6. Retrieve results by using ResultSet interface

    7. Close Statement and Connection

    We will look at these areas one by one, what type of driver you need to load, how to use Connection interface in the best manner, how to use different Statement interfaces, how to process results using ResultSet and finally how to optimize SQL queries to improve JDBC performance.

    Note1: Your JDBC driver should be fully compatible with JDBC 2.0 features in order to use some of the suggestions mentioned in this section.

    Note2: This Section assumes that reader has some basic knowledge of JDBC.

    Choosing right Driver

    Here we will walk through initially about the types of drivers, availability of drivers, use of drivers in different situations, and then we will discuss about which driver suits your application best.

    Driver is the key player in a JDBC application, it acts as a mediator between Java application and database. It implements JDBC API interfaces for a database, for example Oracle driver for oracle database, Sybase driver for Sybase database. It maps Java language to database specific language including SQL.

    JDBC defines four types of drivers to work with. Depending on your requirement you can choose one among them.

    Here is a brief description of each type of driver :

    Type of driver

    Tier

    Driver mechanism

    Description

    1

    Two

    JDBC-ODBC

    This driver converts JDBC calls to ODBC calls through JDBC-ODBC Bridge driver which in turn converts to database calls. Client requires ODBC libraries.

    2

    Two

    Native API - Partly - Java driver

    This driver converts JDBC calls to database specific native calls. Client requires database specific libraries.

    3

    Three

    JDBC - Net -All Java driver

    This driver passes calls to proxy server through network protocol which in turn converts to database calls and passes through database specific protocol. Client doesn't require any driver.

    4

    Two

    Native protocol - All - Java driver

    This driver directly calls database. Client doesn't require any driver.

    Obviously the choice of choosing a driver depends on availability of driver and requirement. Generally all the databases support their own drivers or from third party vendors. If you don't have driver for your database, JDBC-ODBC driver is the only choice because all most all the vendors support ODBC. If you have tiered requirement ( two tier or three tier) for your application, then you can filter down your choices, for example if your application is three tiered, then you can go for Type three driver between client and proxy server shown below. If you want to connect to database from java applet, then you have to use Type four driver because it is only the driver which supports that feature. This figure shows the overall picture of drivers from tiered perspective.

    This figure illustrates the drivers that can be used for two tiered and three tiered applications. For both two and three tiered applications, you can filter down easily to Type three driver but you can use Type one, two and four drivers for both tiered applications. To be more precise, for java applications( non-applet) you can use Type one, two or four driver. Here is exactly where you may make a mistake by choosing a driver without taking performance into consideration. Let us look at that perspective in the following section.

    Type 3 & 4 drivers are faster than other drivers because Type 3 gives facility for optimization techniques provided by application server such as connection pooling, caching, load balancing etc and Type 4 driver need not translate database calls to ODBC or native connectivity interface. Type 1 drivers are slow because they have to convert JDBC calls to ODBC through JDBC-ODBC Bridge driver initially and then ODBC Driver converts them into database specific calls. Type 2 drivers give average performance when compared to Type 3 & 4 drivers because the database calls have to be converted into database specific calls. Type 2 drivers give better performance than Type 1 drivers.

    Finally, to improve performance

    1. Use Type 4 driver for applet to database communication.

    2. Use Type 2 driver for two tiered applications for communication between java client and the database that gives better performance when compared to Type1 driver

    3. Use Type 1 driver if your database doesn't support a driver. This is rare situation because almost all major databases support drivers or you will get them from third party vendors.

    4.Use Type 3 driver to communicate between client and proxy server ( weblogic, websphere etc) for three tiered applications that gives better performance when compared to Type 1 & 2 drivers.

    Optimization with Connection

    java.sql package in JDBC provides Connection interface that encapsulates database connection functionality. Using Connection interface, you can fine tune the following operations :

    1. Set optimal row pre-fetch value

    2. Use Connection pool

    3. Control transaction

    4. Choose optimal isolation level

    5. Close Connection when finished

    Each of these operations effects the performance. We will walk through each operation one by one.

    1. Set optimal row pre-fetch value

    We have different approaches to establish a connection with the database, the first type of approach is :

    1. DriverManager.getConnection(String url)

    2. DriverManager.getConnection(String url, Properties props)

    3. DriverManager.getConnection(String url, String user, String password)

    4. Driver.connect(String url, Properties props)

    When you use this approach, you can pass database specific information to the database by passing properties using Properties object to improve performance. For example, when you use oracle database you can pass default number of rows that must be pre-fetched from the database server and the default batch value that triggers an execution request. Oracle has default value as 10 for both properties. By increasing the value of these properties, you can reduce the number of database calls which in turn improves performance. The following code snippet illustrates this approach.

    java.util.Properties props = new java.util.Properties();

    props.put("user","scott");

    props.put("password","tiger");

    props.put("defaultRowPrefetch","30");

    props.put("defaultBatchValue","5");

    Connection con = DriverManger.getConnection("jdbc:oracle:thin:@hoststring", props);

    You need to figure out appropriate values for above properties for better performance depending on application's requirement. Suppose, you want to set these properties for search facility, you can increase defaultRowPrefetch so that you can increase performance significantly.

    The second type of approach is to get connection from DataSource.

    You can get the connection using javax.sql.DataSource interface. The advantage of getting connection from this approach is that the DataSource works with JNDI. The implementation of DataSource is done by vendor, for example you can find this feature in weblogic, websphere etc. The vendor simply creates DataSource implementation class and binds it to the JNDI tree. The following code shows how a vendor creates implementation class and binds it to JNDI tree.

    DataSourceImpl dsi = new DataSourceImpl();

    dsi.setServerName("oracle8i");

    dsi.setDatabaseName("Demo");

    Context ctx = new InitialContext();

    ctx.bind("jdbc/demoDB", dsi);

    This code registers the DataSourceImpl object to the JNDI tree, then the programmer can get the DataSource reference from JNDI tree without knowledge of the underlying technology.

    Context ctx = new InitialContext();

    DataSource ds = (DataSource)ctx.lookup("jdbc/demoDB");

    Connection con = ds.getConnection();

    By using this approach we can improve performance. Nearly all major vendor application servers like weblogic, webshpere implement the DataSource by taking connection from connection pool rather than a single connection every time. The application server creates connection pool by default. We will discuss the advantage of connection pool to improve performance in the next section.

    2. Use Connection pool

    Creating a connection to the database server is expensive. It is even more expensive if the server is located on another machine. Connection pool contains a number of open database connections with minimum and maximum connections, that means the connection pool has open connections between minimum and maximum number that you specify. The pool expands and shrinks between minimum and maximum size depending on incremental capacity. You need to give minimum, maximum and incremental sizes as properties to the pool in order to maintain that functionality. You get the connection from the pool rather directly .For example, if you give properties like min, max and incremental sizes as 3, 10 and 1 then pool is created with size 3 initially and if it reaches it's capacity 3 and if a client requests a connection concurrently, it increments its capacity by 1 till it reaches 10 and later on it puts all its clients in a queue.

    There are a few choices when using connection pool.

    1. You can depend on application server if it supports this feature, generally all the application servers support connection pools. Application server creates the connection pool on behalf of you when it starts. You need to give properties like min, max and incremental sizes to the application server.

    2. You can use JDBC 2.0 interfaces, ConnectionPoolDataSource and PooledConnection if your driver implements these interfaces

    3. Or you can create your own connection pool if you are not using any application server or JDBC 2.0 compatible driver.

    By using any of these options, you can increase performance significantly. You need to take care of properties like min, max and incremental sizes. The maximum number of connections to be given depends on your application's requirement that means how many concurrent clients can access your database and also it depends up on your database's capability to provide maximum number of connections.

    3. Control transaction

    In general, transaction represents one unit of work or bunch of code in the program that executes in it's entirety or none at all. To be precise, it is all or no work. In JDBC, transaction is a set of one or more Statements that execute as a single unit.

    java.sql.Connection interface provides some methods to control transaction they are

    public interface Connection {

    boolean getAutoCommit();

    void setAutoCommit(boolean autocommit);

    void commit();

    void rollback();

    }

    JDBC's default mechanism for transactions:

    By default in JDBC transaction starts and commits after each statement's execution on a connection. That is the AutoCommit mode is true. Programmer need not write a commit() method explicitly after each statement.

    Obviously this default mechanism gives good facility for programmers if they want to execute a single statement. But it gives poor performance when multiple statements on a connection are to be executed because commit is issued after each statement by default, that in turn reduces performance by issuing unnecessary commits. The remedy is to flip it back to AutoCommit mode as false and issue commit() method after a set of statements execute, this is called as batch transaction. Use rollback() in catch block to rollback the transaction whenever an exception occurs in your program. The following code illustrates the batch transaction approach.

    try{

    connection.setAutoCommit(false);

    PreparedStatement ps = connection.preareStatement( "UPDATE employee SET Address=? WHERE name=?");

    ps.setString(1,"Austin");

    ps.setString(2,"RR");

    ps.executeUpdate();

    PreparedStatement ps1 = connection.prepareStatement( "UPDATE account SET salary=? WHERE name=?");

    ps1.setDouble(1, 5000.00);

    ps1.setString(2,"RR");

    ps1.executeUpdate();

    connection.commit();

    connection.setAutoCommit(true);

    }catch(SQLException e){ connection.rollback();}

    finally{

    if(ps != null){ ps.close();}

    if(ps1 != null){ps1.close();}

    if(connection != null){connection.close();}

    }

    This batch transaction gives good performance by reducing commit calls after each statement's execution.

    4. Choose optimal isolation level

    Isolation level represent how a database maintains data integrity against the problems like dirty reads, phantom reads and non-repeatable reads which can occur due to concurrent transactions. java.sql.Connection interface provides methods and constants to avoid the above mentioned problems by setting different isolation levels.

    public interface Connection {

    public static final int TRANSACTION_NONE = 0

    public static final int TRANSACTION_READ_COMMITTED = 2

    public static final int TRANSACTION_READ_UNCOMMITTED = 1

    public static final int TRANSACTION_REPEATABLE_READ = 4

    public static final int TRANSACTION_SERIALIZABLE = 8

    int getTransactionIsolation();

    void setTransactionIsolation(int isolationlevelconstant);

    }

    You can get the existing isolation level with getTransactionIsolation() method and set the isolation level with setTransactionIsolation(int isolationlevelconstant) by passing above constants to this method.

    The following table describes isolation level against the problem that it prevents :

    Transaction Level

    Permitted Phenomena

    Performance impact

    Dirty reads

    Non Repeatable reads

    Phantom reads

    TRANSACTION_NONE

    N/A

    N/A

    N/A

    FASTEST

    TRANSACTION_READ_UNCOMMITED

    YES

    YES

    YES

    FASTEST

    TRANSACTION_READ_COMMITED

    NO

    YES

    YES

    FAST

    TRANSACTION_REPEATABLE_READ

    NO

    NO

    YES

    MEDIUM

    TRANSACTION_SERIALIZABLE

    NO

    NO

    NO

    SLOW

    YES means that the Isolation level does not prevent the problem

    NO means that the Isolation level prevents the problem

    By setting isolation levels, you are having an impact on the performance as mentioned in the above table. Database use read and write locks to control above isolation levels. Let us have a look at each of these problems and then look at the impact on the performance.

    Dirty read problem :

    The following figure illustrates Dirty read problem :

    Step 1: Database row has PRODUCT = A001 and PRICE = 10

    Step 2: Connection1 starts Transaction1 (T1) .

    Step 3: Connection2 starts Transaction2 (T2) .

    Step 4: T1 updates PRICE =20 for PRODUCT = A001

    Step 5: Database has now PRICE = 20 for PRODUCT = A001

    Step 6: T2 reads PRICE = 20 for PRODUCT = A001

    Step 7: T2 commits transaction

    Step 8: T1 rollbacks the transaction because of some problem

    The problem is that T2 gets wrong PRICE=20 for PRODUCT = A001 instead of 10 because of uncommitted read. Obviously it is very dangerous in critical transactions if you read inconsistent data. If you are sure about not accessing data concurrently then you can allow this problem by setting TRANSACTION_READ_UNCOMMITED or TRANSACTION_NONE that in turn improves performance otherwise you have to use TRANSACTION_READ_COMMITED to avoid this problem.

    Unrepeatable read problem :

    The following figure illustrates Unrepeatable read problem :

    Step 1: Database row has PRODUCT = A001 and PRICE = 10

    Step 2: Connection1 starts Transaction1 (T1) .

    Step 3: Connection2 starts Transaction2 (T2) .

    Step 4: T1 reads PRICE =10 for PRODUCT = A001

    Step 5: T2 updates PRICE = 20 for PRODUCT = A001

    Step 6: T2 commits transaction

    Step 7: Database row has PRODUCT = A001 and PRICE = 20

    Step 8: T1 reads PRICE = 20 for PRODUCT = A001

    Step 9: T1 commits transaction

    Here the problem is that Transaction1 reads 10 first time and reads 20 second time but it is supposed to be 10 always whenever it reads a record in that transaction. You can control this problem by setting isolation level as TRANSACTION_REPEATABLE_READ.

    Phantom read problem :

    The following figure illustrates Phantom read problem :

    Step 1: Database has a row PRODUCT = A001 and COMPANY_ID = 10

    Step 2: Connection1 starts Transaction1 (T1) .

    Step 3: Connection2 starts Transaction2 (T2) .

    Step 4: T1 selects a row with a condition SELECT PRODUCT WHERE COMPANY_ID = 10

    Step 5: T2 inserts a row with a condition INSERT PRODUCT=A002 WHERE

    COMPANY_ID= 10

    Step 6: T2 commits transaction

    Step 7: Database has 2 rows with that condition

    Step 8: T1 select again with a condition SELECT PRODUCT WHERE COMPANY_ID=10

    and gets 2 rows instead of 1 row

    Step 9: T1 commits transaction

    Here the problem is that T1 gets 2 rows instead of 1 row up on selecting the same condition second time. You can control this problem by setting isolation level as TRANSACTION_SERIALIZABLE

    Choosing a right isolation level for your program:

    Choosing a right isolation level for your program depends upon your application's requirement. In single application itself the requirement generally changes, suppose if you write a program for searching a product catalog from your database then you can easily choose TRANSACTION_READ_UNCOMMITED because you need not worry about the problems that are mentioned above, some other program can insert records at the same time, you don't have to bother much about that insertion. Obviously this improves performance significantly.

    If you write a critical program like bank or stocks analysis program where you want to control all of the above mentioned problems, you can choose TRANSACTION_SERIALIZABLE for maximum safety. Here it is the tradeoff between the safety and performance. Ultimately we need safety here.

    If you don't have to deal with concurrent transactions your application, then the best choice is TRANSACTION_NONE to improve performance.

    Other two isolation levels need good understanding of your requirement. If your application needs only committed records, then TRANSACTION_READ_COMMITED isolation is the good choice. If your application needs to read a row exclusively till you finish your work, then TRANSACTION_REPEATABLE_READ is the best choice.

    Note: Be aware of your database server's support for these isolation levels. Database servers may not support all of these isolation levels. Oracle server supports only two isolation levels, TRANSACTION_READ_COMMITED and TRANSACTION_SERIALIZABLE isolation level, default isolation level is TRANSACTION_READ_COMMITED.

    5. Close Connection when finished

    Closing connection explicitly allows garbage collector to recollect memory as early as possible. Remember that when you use the connection pool, closing connection means that it returns back to the connection pool rather than closing direct connection to the database.

    Optimization with Statement

    Statement interface represents SQL query and execution and they provide number of methods and constants to work with queries. They also provide some methods to fine tune performance. Programmer may overlook these fine tuning methods that result in poor performance. The following are the tips to improve performance by using statement interfaces

    1. Choose the right Statement interface

    2. Do batch update

    3. Do batch retrieval using Statement

    2. Close Statement when finished

    1. Choose right Statement interface

    There are three types of Statement interfaces in JDBC to represent the SQL query and execute that query, they are Statement, PreparedStatement and CallableStatement.

    Statement is used for static SQL statement with no input and output parameters, PreparedStatement is used for dynamic SQL statement with input parameters and CallableStatement is used for dynamic SQL satement with both input and output parameters, but PreparedStatement and CallableStatement can be used for static SQL statements as well. CallableStatement is mainly meant for stored procedures.

    PreparedStatement gives better performance when compared to Statement because it is pre-parsed and pre-compiled by the database once for the first time and then onwards it reuses the parsed and compiled statement. Because of this feature, it significantly improves performance when a statement executes repeatedly, It reduces the overload incurred by parsing and compiling.

    CallableStatement gives better performance when compared to PreparedStatement and Statement when there is a requirement for single request to process multiple complex statements. It parses and stores the stored procedures in the database and does all the work at database itself that in turn improves performance. But we loose java portability and we have to depend up on database specific stored procedures.

    2. Do batch update

    You can send multiple queries to the database at a time using batch update feature of statement objects this reduces the number of JDBC calls and improves performance. Here is an example of how you can do batch update,

    statement.addBatch( "sql query1");

    statement.addBatch(" sql query2");

    statement.addBatch(" sql query3");

    statement.executeBatch();

    All three types of statements have these methods to do batch update.

    3. Do batch retrieval using Statement

    You can get the default number of rows that is provided by the driver. You can improve performance by increasing number of rows to be fetched at a time from database using setFetchSize() method of the statement object.

    Initially find the default size by using

    Statement.getFetchSize(); and then set the size as per your requirement

    Statement.setFetchSize(30);

    Here it retrieves 30 rows at a time for all result sets of this statement.

    4. Close Statement when finished

    Close statement object as soon as you finish working with that, it explicitly gives a chance to garbage collector to recollect memory as early as possible which in turn effects performance.

    Statement.close();

    Optimization with ResultSet

    ResultSet interface represents data that contains the results of executing an SQL Query and it provides a number of methods and constants to work with that data. It also provides methods to fine tune retrieval of data to improve performance. The following are the fine tuning tips to improve performance by using ResultSet interface.

    1. Do batch retrieval using ResultSet

    2. Set up proper direction for processing the rows

    3. Use proper get methods

    4. Close ResultSet when finished

    1. Do batch retrieval using ResultSet

    ResultSet interface also provides batch retrieval facility like Statement as mentioned above. It overrides the Statement behaviour.

    Initially find the default size by using

    ResultSet.getFetchSize(); and then set the size as per requirement

    ResultSet.setFetchSize(50);

    This feature significantly improves performance when you are dealing with retrieval of large number of rows like search functionality.

    2. Setup proper direction of processing rows

    ResultSet has the capability of setting the direction in which you want to process the results, it has three constants for this purpose, they are

    FETCH_FORWARD, FETCH_REVERSE, FETCH_UNKNOWN

    Initially find the direction by using

    ResultSet.getFetchDirection(); and then set the direction accordingly

    ResultSet.setFetchDirection(FETCH_REVERSE);

    3. Use proper getxxx() methods

    ResultSet interface provides lot of getxxx() methods to get and convert database data types to java data types and is flexibile in converting non feasible data types. For example,

    getString(String columnName) returns java String object.

    columnName is recommended to be a VARCHAR OR CHAR type of database but it can also be a NUMERIC, DATE etc.

    If you give non recommended parameters, it needs to cast it to proper java data type that is expensive. For example consider that you select a product's id from huge database which returns millions of records from search functionality, it needs to convert all these records that is very expensive.

    So always use proper getxxx() methods according to JDBC recommendations.

    4. Close ResultSet when finished

    Close ResultSet object as soon as you finish working with ResultSet object even though Statement object closes the ResultSet object implicitly when it closes, closing ResultSet explicitly gives chance to garbage collector to recollect memory as early as possible because ResultSet object may occupy lot of memory depending on query.

    ResultSet.close();

    Optimization with SQL Query

    This is one of the area where programmers generally make a mistake

    If you give a query like

    Statement stmt = connection.createStatement();

    ResultSet rs = stmt.executeQuery("select * from employee where name=RR");

    The returned result set contains all the columns data. you may not need all the column data and want only salary for RR.

    The better query is "select salary from employee where name=RR"

    It returns the required data and reduces unnecessary data retrieval.

    Cache the read-only and read-mostly data

    Every database schema generally has read-only and read-mostly tables. These tables are called as lookup tables. Read-only tables contain static data that never changes in its life time. Read-mostly tables contain semi dynamic data that changes often. There will not be any sort of writing operations in these tables.

    If an application reads data from these tables for every client request, then it is redundant, unnecessary and expensive. The solution for this problem is to cache the read-only table data by reading the data from that table once and caching the read-mostly table data by reading and refreshing with time limit. This solution improves performance significantly. See the following link for source code of such caching mechanism.

    http://www.javaworld.com/javaworld/jw-07-2001/jw-0720-cache.html

    You can tweak this code as per application requirement. For read-only data, you need not refresh data in its life time. For read-mostly data, you need to refresh the data with time limit. It is better to set this refreshing time limit in properties file so that it can be changed at any time.

    Fetch small amount of data iteratively instead of fetching whole data at once

    Applications generally require to retrieve huge data from the database using JDBC in operations like searching data. If the client request for a search, the application might return the whole result set at once. This process takes lot of time and has an impact on performance. The solution for the problem is

    1. Cache the search data at the server-side and return the data iteratively to the client. For example, the search returns 1000 records, return data to the client in 10 iterations where each iteration has 100 records.

    2. Use Stored procedures to return data iteratively. This does not use server-side caching rather server-side application uses Stored procedures to return small amount of data iteratively.

    Out of these solutions the second solution gives better performance because it need not keep the data in the cache (in-memory). The first procedure is useful when the total amount of data to be returned is not huge.

    Key Points

  1. Use Type two driver for two tiered applications to communicate from java client to database that gives better performance than Type1 driver.
  2. Use Type four driver for applet to database communication that is two tiered applications and three tiered applications when compared to other drivers.
  3. Use Type one driver if you don't have a driver for your database. This is a rare situation because all major databases support drivers or you will get a driver from third party vendors.
  4. Use Type three driver to communicate between client and proxy server ( weblogic, websphere etc) for three tiered applications that gives better performance when compared to Type 1 &2 drivers.
  5. Pass database specific properties like defaultPrefetch if your database supports any of them.
  6. Get database connection from connection pool rather than getting it directly
  7. Use batch transactions.
  8. Choose right isolation level as per your requirement. TRANSACTION_READ_UNCOMMITED gives best performance for concurrent transaction based applications. TRANSACTION_NONE gives best performance for non-concurrent transaction based applications.
  9. Your database server may not support all isolation levels, be aware of your database server features.
  10. Use PreparedStatement when you execute the same statement more than once.
  11. Use CallableStatement when you want result from multiple and complex statements for a single request.
  12. Use batch update facility available in Statements.
  13. Use batch retrieval facility available in Statements or ResultSet.
  14. Set up proper direction for processing rows.
  15. Use proper getXXX() methods.
  16. Close ResultSet, Statement and Connection whenever you finish your work with them.
  17. Write precise SQL queries.
  18. Cache read-only and read-mostly tables data.
  19. Fetch small amount of data iteratively rather than whole data at once when retrieving large amount of data like searching database etc.
  20. Source from <http://www.precisejava.com/javaperf/j2ee/JDBC.htm>

123passportphoto is a very easy to use passport photo website that provides six enhanced photos. I have never had an issue while using this ...