J2EE notes
J2EE notes
Model Programs: There are many styles can be used to write the data access portion of a J2EE
component. The Model A program style is used to execute SQL requests that use the execute ()
or executeUpdate() method and donot return ResultSet. The Model B program style is used to
execute SQL requests that use the executeQuery() method which returns a ResultSet.
Both program styles are designed to minimize the code clutter.
Model A Program:
import java.sql.*;
public class ModelA
{
private Connection database;
private Statement DataRequest;
public ModelA()
{
String url=“”;
String userID=“”;
String password=“”;
try{
Class.forName(“”);
Database=DriverManager.getConnection(url,userID,password);
}
catch (ClassNotFoundException error) {
System.err.println(“” + error);
System.exit(1);
}
catch (SQLException error){
System.err.println{“” + error);
If(Database != null){
try{
Databse.close();
}
Catch(SQLException er) {}
}
System.exit(2);
}
try{
// insert example code here
}
catch(SQLException error){
System.err.println(“” + error);
if(Database != null) {
try{
Database.close();
}
catch(SQLException er) {}
}
System.exit(3);
}
if(Database != null){
try{
Database.close();
}
catch(SQLException er){}
}
}
public static void main(String args[])
{
final ModelA sql1=new ModelA();
System.exit(0);
}
}
Model B Programming:
The Model B program is designed for use by J2EE components that retrieve information from a
database. Model B program is similar to the Mode A program in that the constructor definitions
and the main() are identical.
Model B contains DisplayResults() and DownRow(). DisplayResults() is passed the ResultSet
returned in the second try{} block. Which is used to move the virtual cursor to the first row of
the ResultSet using the next() method. The next() returns value of Records and displays a “no
data returned” message if records contains a false value indicating the there is not any data in the
row. DownRow() extracts data from the current row of the ResultSet, control returns to
DisplayResults() where the next() methos is called and the results are evaluated by the do..while
loop is exited and control returns to the constructor.
import java.sql.*;
public class ModelB
{
private Connection Database;
private Statement DataRequest;
private ResultSet Results;
public ModelB()
{
String url=“”;
String userID=“”;
String password=“”;
try{
Class.forName(“”);
Database=DriverManager.getConnection(url,userID,password);
}
catch (ClassNotFoundException error) {
System.err.println(“” + error);
System.exit(1);
}
catch (SQLException error){
System.err.println{“” + error);
System.exit(2);
}
try{
// insert example code here
}
catch(SQLException error){
System.err.println(“” + error);
if(Database != null) {
try{
Database.close();
}
catch(SQLException er) {}
}
System.exit(3);
}
if (Database != null){
try{
Database.close();
}
catch(SQLException er){}
}
}
private void DisplayResults(ResultSet DisplayResults) throws SQLException
{
boolean Records=DisplayResults.next();
if(!Records){
System.out.println(“No data returned”);
return;
}
try{
do{
DownRow(DisplayResults);
} while(DisplayResults.next());
}
catch(SQLException error){
System.err.println(“Data display error” + error);
if(Database != null) {
try{
Database.close();
}
catch(SQLException er) {}
}
System.exit(4);
}
}
private void DownRow(ResultSet DisplayResults) throws SQLException
{
//Enter new Downrow() code here
}
public static void main(String args[])
{
final ModelB sql1=new ModelB);
System.exit(0);
}
}
Table:
Tables are database objects that contain all the data in a database. In tables, data is logically
organized in a row-and-column format similar to a spreadsheet. Each row represents a unique
record, and each column represents a field in the record.
Creating a Table:
We can create a table by formatting a SQL query. The query contains the Create Table SQL
statement that contains the name of the table. All sql commands are enclosed in double
quotations and assigned to a String object called query. Next the program creates a SQL
statement using the createStatement() method of the Connection object. This method returns the
handle to the DBMS to the DataRequest object which is an object of the Statement class.
Example:
String query=”create table customeraddress(“+”customernumber integer,”+”customerstreet
char(30),”+”customercity char(30),+”customerzip char(30))”;
DataRequest=Database.createStatment();
DataRequest.execute(query);
DataRequest.close();
}
Dropping Table:
A developer may have the right to remove a table, but this is usually reserved for the
development environment only. Once the table is dropped its not possible to recover the table. In
addition to losing data elements stored in the table, dropping a table may also affect the integrity
of the database and tables that relate to values in the dropped table.
Example:
try{
String query=new String(“Drop table customeraddress”);
DataRequest=Database.createStatement();
DataRequest=execute(query);
DataRequest.close();
}
Art of Indexing:
When records are stored in the primary memory like RAM, accessing them is very easy and
quick. But records are not limited in numbers to store in RAM. They are very huge and we have
to store it in the secondary memories like hard disk. In memory we cannot store records like we
see – tables. They are stored in the form of files in different data blocks. Each block is capable
of storing one or more records depending on its size. When we have to retrieve any required data
or perform some transaction on those data, we have to pull them from memory, perform the
transaction and save them back to the memory.
In order to do all these activities, we need to have a link between the records and the data blocks
so that we can know where these records are stored. This link between the records and the data
block is called index. It acts like a bridge between the records and the data block.
How do we index in a book? We list main topics first and under that we group different sub-topic
right?
We do the same thing in the database too. Each table will have unique column or primary key
column which uniquely determines each record in the table. Most of the time, we use this
primary key to create index. Sometimes, we will have to fetch the records based on other
columns in the table which are not primary key. In such cases we create index on those columns.
Index in databases is the pointer to the block address in the memory. But these pointers are
stored as (column, block_address) format.
Example:
Imagine we have a student table with thousands of records, each of which is 10 bytes long.
Imagine their IDs start from 1 2, 3… and goes on. And we have to search student with ID 678.
In a normal database with no index, it searches the disk block from the beginning till it reaches
678. So the DBMS will reach this record after reading 677*10 = 6770 bytes. But if we have
index on ID column, then the address of the location will be stored as each record as (1,200), (2,
201)… (678, 879) and so on. One can imagine it as a smaller table with index column and
address column. Now if we want to search record with ID 678, then it will search using indexes.
i.e.; here it will traverse only 677*2 = 1354 bytes which very less compared to earlier one. Hence
retrieving the record from the disk becomes faster.
• Most of the cases these indexes are sorted and kept to make searching faster.
• If the indexes are sorted, then it is called as ordered indices.
Types of Indexing:
try{
String query=new String(“select FirstName, LastName from customers where lanstname=’Mary’
NOT FirstName=’Bob’”);
DataRequest=Database.createStatement();
Results=DataRequest.executeQuery(query);
DisplayResults(Results);
DataRequest.close();
}
Joining Multiple Compound Expression:
• The AND and OR clauses are used to link together two or more subexpressions. This
results in compound expression.
• There can be multiple compound expressions within a WHERE clause expression.
• AND clause has a higher precedence than the OR clause, so the OR clause must be
placed within parenthesis.
• Example:
• Select * from customer where FirstaName=‘bob’and LastName=‘smith AND (Dept=‘42’
OR Dept=‘45’)
Equal and NOT Equal Operators:
• Equal and Not Equal operators are used to determine if the value in the where clause
expression is or is not in the specify column.
Example:
try{
String query=new String(“Select FirstName,LastName,Street,City,State from customers
where NOT sales=5000”);
DataRequest=Database.createStatement();
Results=DataRequest.executeQuery(query);
DisplayResults(Results);
DataRequest.close();
}
Private void DownRow(ResultSet displayresults) throws SQLException
{ String FirstName=new String();
String LastName=new String();
String Street=new String();
String City=new String();
String State=new String();
String printrow;
FirstName=displayresults.getString(1);
LastName=displayresults.getString(2);
Street=displayresults.getString(3);
City=displayresults.getString(4);
State=displayresults.getString(5);
printrow=FirstName+””+LastName+””+Street+””+City+””+State;
System.out.println(printrow);
Less Than and Greater Than Operator:
• The less than and greater than operators direct the DBMS to assess whether or not the
value in the specified column of the current row is less than or greater than the value in
the WHERE clause expression.
• The value in a column that equals the value in the WHERE clause expression is evaluated
as a Boolean false.
• The row containing than value is not returned in the ResultSet.
• The value in the column must be less than or greater than, but not equal to the value in
the WHERE clause expression
Example for Less Than:
try{
String query=new String(“Select FirstName,LastName,Street,City,State from customers where
sales<5000;”);
DataRequest=Database.createStatement();
Results=DataRequest.executeQuery(query);
DisplayResults(Results);
DataRequest.close();
}
Example for Greater Than:
try{
String query=new String(“Select FirstName,LastName,Street,City,State from customers where
sales>5000;”);
DataRequest=Database.createStatement();
Results=DataRequest.executeQuery(query);
DisplayResults(Results);
DataRequest.close();
}
Less Than Equal to And Greater Than Equal To:
Less Than Equal To and Greater Than Equal To operators include rows that contain the WHERE
clause expression.
try{
String query=new String(“Select FirstName,LastName,Street,City,State from customers where
sales<=5000;”);
DataRequest=Database.createStatement();
Results=DataRequest.executeQuery(query);
DisplayResults(Results);
DataRequest.close();
}
Example for Greater Than:
try{
String query=new String(“Select FirstName,LastName,Street,City,State from customers where
sales=>5000;”);
DataRequest=Database.createStatement();
Results=DataRequest.executeQuery(query);
DisplayResults(Results);
DataRequest.close();
}
BETWEEN :
• BETWEEN operator is used to define a range of values that is to be used as the value of
the selection expression.
• The range must consist of a sequential series of values such as from 100 to 200.
• The BETWEEN operator must follow the name of the column in the WHERE clause.
• The AND operator is used to join the lower and upper values of he range.
• All the values in the range including first and last values are considered when the DBMS
evaluates the value of the column specified in the selection expression
Example:
try{
String query=new String(“Select FirstName,LastName,Street,City,State from customers where
sales BETWEEN 20000 AND 39999”);
DataRequest=Database.createStatement();
Results=DataRequest.executeQuery(query);
DisplayResults(Results);
DataRequest.close();
}
LIKE Operator:
• LIKE operator directs the DBMS to return a row in the ResultSet if a value in a specified
column partially matches the value of the WHERE clause expression.
• The WHERE clause expression must include a character that must be an exact match and
a wildcard character that is used to match any other character.
• Wildcards used with the LIKE operator:
• Underscore(_): A single character wildcard character.
Eg: if we are unsure if the customer last name is Anderson or Andersesn, we use the
underscore in place of the character that is in the question such as Anders_n.
• Percent(%): a multicharacter wildcard used to match any number of characters.
Eg: Smi% is used to match a value of a column where the first three characters are Smi
and any other characters.
Example:
try{
String query=new String(“Select FirstName,LastName,Street,City,State from customers where
LastName LIKE ‘Smi%’”);
DataRequest=Database.createStatement();
Results=DataRequest.executeQuery(query);
DisplayResults(Results);
DataRequest.close();
}
IS NULL Operator:
• IS NULL operator is used to determine if a specified column does not contain any value.
• We use IS NULL operator whenever we need to identify rows that are missing
information in a column.
• It is important to understand that the number zero or a space are not NULL values.
• Eg: Zero value in the sales column of a table is a real value
• A column that contains space isnot NULL, because a space is a valid ASCII character
• NULL is void of any value and occurs when a row is inserted into a table without having
a value or the value is explicitly set to NULL
Example:
try{
String query=new String(“Select FirstName,LastName,Street,City,State from customers where
State is NULL”);
DataRequest=Database.createStatement();
Results=DataRequest.executeQuery(query);
DisplayResults(Results);
DataRequest.close();
}
DISTINCT Modifier:
• The select statement returns all the rows in a table unless a where clause is used to
exclude specific rows.
• ResultSet includes duplicate rows unless a primary index is created for the table or only
unique rows are required in the table.
• When we want to exclude all but one copy of a row from the ResultSet we can use
DISTINCT modifier in the select statement.
• The DISTINCT modifier tells eh DBMS not to include duplicate rows in the resultset
Example:
try{
String query=new String(“Select DISTINCT FirstName,LastName,Street,City,State from
customers”);
DataRequest=Database.createStatement();
Results=DataRequest.executeQuery(query);
DisplayResults(Results);
DataRequest.close();
}
IN Modifier:
• IN modifier is used to define a set of values used by the DBMS to match values in a
specified column.
• The set can include any number of values and appear in any order.
• The IN modifier is used in the WHERE clause to define the list of values in the set
Example:
try{
String query=new String(“Select FirstName,LastName,Street,City,State from customers where
sales IN (20000,30000,40000)”);
DataRequest=Database.createStatement();
Results=DataRequest.executeQuery(query);
DisplayResults(Results);
DataRequest.close();
}
• If any of these three values are found in the sales column of the current row, the row is
returned to the program.
NOT IN Modifier:
• The NOT IN modifier is similar to the IN modifier except in the NOT IN modifier
reverses the logic of the previous selection expression.
• NOT IN modifier identifies a set of values that shoulnot match rows returned to the
program.
try{
String query=new String(“Select FirstName,LastName,Street,City,State from customers where
sales NOT IN (20000,30000,40000)”);
DataRequest=Database.createStatement();
Results=DataRequest.executeQuery(query);
DisplayResults(Results);
DataRequest.close();
}
• Here all columns of rows in the customers table where the value of the sales column is
not 20000,30000,40000 are returned in the resultset.
• Rows with sales of 20000,30000,40000 are not returned .
Metadata:
Metadata is data that describes data. Metadata is returned with the ReslutSet object and
can be extracted from the ResultSet object by creating a ResultSetMetaData.
Metadata in J2EE can be used in J2EE component for various purposes such as to display
the column name of a column and determine the datatype of a column among other
meatadata
Commonly used metadata are :
Column Name
Column Number
Column data type
Column width
• A JOIN clause is used to combine rows from two or more tables, based on a related
column between them.
• Tables are joined in a query using two step process
• First both tables that are being joined must be identified in the FROM clause where tables
are listed one after the other and are separated by a comma
• Next an expression is created in the WHERE clause that identifies the columns that are
used to create the join.
• The joined tables create a logical table that has all the columns of both tables.
• Joining too many tables can cause performance degradation and bring response time to a
crawl.
Example Tables:
try{
String query=new String(“select FirstName,LastName,City,State,Zipcode from
customers,zipcode where zip=zipcode”);
Stmt=con.createStatement();
Results=stmt.executeQuery(query);
Private void downrow(ResultSet rs)
{
String fn=new String();
String ln=new String();
String street=new String();
String city=new String();
String state=new String();
String zipcode=new String();
String printrow;
fn=rs.getString(1);
Ln=rs.getString(2);
Street=rs.getString(3);
City=rs.getString(4);
State=rs.getString(5);
Zipcode=rs.getString(6);
Printrow=FirstName+” ”+LastName+” ”+city+””+State+””+zipcode;
System.out.println(printrow);}
Parent-Child Join:
• A parent/child join is used to join tables that have a parent/child relationship where rows
in the parent table must exist for rows in the child table to exist
• Only rows that have a matching product number in both tables are placed in the virtual
table that consists of rows from both tables
• Customer cannot order a product that does not exist in the Products table.
• Here product is parent table and order is child table.
try{
String query=new String(“select ordernumber, productname from orders, products where
prodnumber=ProductNumber”);
Stmt=con.createStatement();
Results=stmt.executeQuery(query);
Private void downrow(ResultSet rs)
{
int ordernum,prodnum
String printrow=new String();
ordernum=rs.getInt(1);
Prodnum=rs.getInt(2);
Printrow=ordernum+” ”+prodnum;
System.out.println(printrow);
}
Multiple Comparison Join:
• WHERE clause expression used to join together tables can be a compound expression
• A compound expression consist of two or more subexpressions each of which evaluated
separately
• A compound expression is used to specify more than one selection criteria used to join
two tables
try{
String query=new String(“select ordernumber, productname ,quantity from orders, products
where prodnumber=ProductNumber and quantity>2”);
Stmt=con.createStatement();
Results=stmt.executeQuery(query);
Private void downrow(ResultSet rs)
{
int ordernum,prodnum,quantity;
String printrow=new String();
ordernum=rs.getInt(1);
Prodnum=rs.getInt(2);
Quantity=rs.getInt(3);
Printrow=ordernum+” ”+prodnum+””+quantity;
System.out.println(printrow);
}
Multitable Join
• More than two tables can be joined together by using the name of each table in he join in
the FROM clause and by defining the join with the appropriate column names in the
WHERE clause expression
• All the tables donot need to have a common value used to join them
try{
String query=new String(“select FirstName,LastName,ordernumber, productname ,quantity
from customers, orders, products where prodnumber=ProductNumber and
custnumber=customernumber”);
Stmt=con.createStatement();
Results=stmt.executeQuery(query);
Private void downrow(ResultSet rs)
{
int ordernum,prodnum,quantity;
String printrow=new String();
String fn=new String();
String ln=new String();
String pn=new String();
Fn=rs.getString(1);
Ln=rs.getString(2);
ordernum=rs.getInt(3);
Pn=rs.getString(4);
Quantity=rs.getInt(5);
Printrow=FirstName+””+LastName+””+
ordernum+” ”+prodnum+””+quantity;
System.out.println(printrow);
}
Creating Column Name Qualifier:
• Two tables can have the same column name to store the data element
• Conflicts with the column name can be resolved in a join by using a column name
qualifier.
• A column name qualifier identifies the table that contains the column name
try{
String query=new String(“select
customers.custnumber,Firstname,lastname,ordernumbr,productname,quantity from
customers,orders,products where prodnumber=productnumber and
customers.customernumber, orders.customernumber”);
Stmt=con.createStatement();
Results=stmt.executeQuery(query);
Private void downrow(ResultSet rs)
{
int ordernum,prodnum,customernum;
String printrow=new String();
String fn=new String();
String ln=new String();
String pn=new String();
Fn=rs.getString(1);
Ln=rs.getString(2);
ordernum=rs.getInt(3);
Pn=rs.getString(4);
Quantity=rs.getInt(5);
Customernum=rs.getInt();
Printrow=fn+””+ln+””+
ordernum+” ”+pn+””+quantity;
System.out.println(printrow);
}
Creating Table Alias:
• A query can be made readable by using table aliases.
• A table alias is an abbreviation for the name of the table and is used in place of the table
name in the join and in the SELECT statement.
• Conditions for making table alias
• With as few letters as possible to save space in the query string
• Representative of the table name, such as the first letter of the table name
• Unique and not a duplicate of another table name, table alias, or column name
try{
String query=new String(“select
c.customernumber,c.firstname,c.lastname,o.ordernumber,p.productname,o.quantity, from
customers c, orders o, products p where o.prodnumber=p.productnumber, and
c.cutomernumber=o.customernumber”);
Stmt=con.createStatement();
Results=stmt.executeQuery(query);}
Inner and Outr Join:
• There are two kinds of joins each of which either excludes or includes rows in both tables
of the join that donot match.
• Inner join: an inner join excluldes rows of either table that donot have a matching
value
• Outer join: an outer join includes rows of either table that donot have a matching
value
Inner Join:
• Inner join is used to include only rows of both tables that have matching values
• Unmatched rows are excluded and therefore those rows are not returned in the ResultSet
try{
String query=new String(“select FirstName, LastName,OrderNumber,ProductName,
Quantity from customers,orders,products where
cusomers.custnumber=orders.customernumber”);
Stmt=con.createStatement();
Results=stmt.executeQuery(query);
Outer Join:- Left, Right, Full
• An outer join occurs when matching and no matching rows of either or both tables are
contained in the join
• There are three kinds of outer joins
1. Left outer join is also known as SQL left join.
• Suppose, we want to join two tables: A and B. Left outer join returns all rows in the left
table (A) and all the matching rows found in the right table (B). It means the result of the
Left join always contains the rows in the left table.
try{
String query=new String(“select FirstName, LastName, OrderNumber from customers
LEFT JOIN orders on customers.custnumber=orders.customernumber”);
o.prodnumber=p.productnumber, and c.cutomernumber=o.customernumber”);
Stmt=con.createStatement();
Results=stmt.executeQuery(query);
• All rows in the customers is listed.
• In case, there is no matching row in the orders table found for the row in
the customers table, the orderid column in the orders table is populated with NULL
values.
Right Outer JOIN:
• Right outer join returns all rows in the right table and all the matching rows found in the
left table.
• All the rows in the orders table are used in the join regardless if the customer number in
the orders table has a corresponding customer number in the customer table.
• The WHERE clause contains the right outer join operator(=*).
try
{
String query=new String(“select FirstName, LastName, OrderNumber from customers
c,orders o where c.custnumber=* o.customernumber”);
Stmt=con.createStatement();
Results=stmt.executeQuery(query);}
Full Outer JOIN
• A full outer join uses all the rows of both tables regardless if they match.
• The full outer join operator(*=*) is a combination of left outer join operator and right
outer join operator.
• We can also use Full JOIN
try
{ String query=new String(“select FirstName, LastName, OrderNumber from customers c,orders
o where c.custnumber*=* o.customernumber”);
Stmt=con.createStatement();
Results=stmt.executeQuery(query);