dash_raym>>Java Tip


EYEBROW: Tips 'N Tricks


Title: Improve your Java code performance by optimizing database interaction.

SHELVING CATEGORY: JDBC Optimization

AUTHOR: Raymond Peter

SUMMARY:

Database interaction has always been a time consuming task, whether it is Oracle, DB2 or Sybase. It seriously hampers the performance of a JSP page. In many JSP/Servlet pages we need to fetch some data which is constant, ie from a master table. This database interaction can be totally eliminated by use of Intelligent Java classes which represent data from these tables and can be implemented in Singleton Pattern.

:END_SUMMARY

BODY:

Ask what hampers a site performance? One of the answers you would get is database interaction. In most cases you need to fetch data from a master table such as:

CREATE TABLE `tb_statemaster`
(
`Pk_StateID` INTEGER (11) NOT NULL  AUTO_INCREMENT ,
`Name` varchar (50) NOT NULL ,
PRIMARY KEY (Pk_StateID)
);

The data in this table remains constant throughout the lifecycle of the application. Consider a page of User Registration which has many fields such as Name, Address, Combo box for States. In normal JSP page this would require Database interaction fetching records from tb_statemaster. This database interaction can be avoided by the use of intelligent Java Beans. These Java Beans loads data once and the data persists throughout the aplication in that bean. If no data is available in the bean it tries to load data from the database.
This article applies to only those tables whose data remains constant throughout. Only one instance of the bean is required, so it can be implemented as Singleton Pattern.

The Java Bean can be coded as follows:

package myclasses;

import java.util.ArrayList;

//Implemented as Singleton Pattern

public class StateMasterData
{
  public static ArrayList states=new ArrayList();
  static boolean isThere=false;
  static StateMasterData s;

  private StateMasterData()  
  {
    if(states.isEmpty())
    {
		System.out.println("instance creating");
		DBConnection db=new DBConnection();
		//javabean to handle database connections
		db.getDBConnection();
		db.getDBStatement();
	    java.sql.ResultSet rs=db.executeDBQuery("select name from tb_statemaster");
		try{
			while(rs.next())
			  states.add(rs.getString("name"));
			rs.close();
		}catch(Exception e) {System.out.println(e);}
		isThere=true;
	}
  }

  public void setStates(ArrayList a)
  {
    states = a;
  }

  public ArrayList getStates()
  {
    return states;
  }

  public static StateMasterData getInstance()
  {
	  if(isThere==false)
		  s=new StateMasterData();
	  return s;
  }
}
:END_BODY

RESOURCES:
none
:END_RESOURCES

BIO:

I am a Senior Software Engineer of Ruchi Infotech Ltd based in Indore, India. I enjoy Java Programming. Its more of a passion than regular work. My intrests include exploring latest technologies and database optimization. To know more about me visit my homepage.

:END_BIO

Hosted by www.Geocities.ws

1