153
POTHURAI Javap : - java profile can be used to see what is there in dot (.) class file. public class Cone { public void mone( ) { // System.out.println("------Cone:mone------"); } } D:\psr\J2EE>javac Cone.java D:\psr\J2EE>javap Cone Compiled from “Cone.java” Public class Cone extends java.lang.object { public Cone( ); public void mone( ); } When the above Cone.java source file is compiled, the java compiler adds a zero (0) arguments constructor for the .class file as the developer as not provided any constructors in the source file. SUDHEER REDDY 1 java.lang.Objec t String toString( ) java.lang.Objec t String toString( )

J2EE Notes

Embed Size (px)

Citation preview

Page 1: J2EE Notes

POTHURAI

Javap: - java profile can be used to see what is there in dot (.) class file.

public class Cone {

public void mone( ){

// System.out.println("------Cone:mone------");}

}

D:\psr\J2EE>javac Cone.javaD:\psr\J2EE>javap ConeCompiled from “Cone.java”Public class Cone extends java.lang.object {

public Cone( );public void mone( );

}When the above Cone.java source file is compiled, the java compiler adds a

zero (0) arguments constructor for the .class file as the developer as not provided any constructors in the source file.

extends

public class Cone1

SUDHEER REDDY

1

java.lang.Object

String toString( )int hashCode( )…..

java.lang.Object

String toString( ) int hashCode( ) …..

Cone

void mone( )Cone( ) added by the compiler

Page 2: J2EE Notes

POTHURAI

{public Cone1(int i){

// System.out.println("------Cone1(int i)------");}public void mone( ){

// System.out.println("------Cone1:mone------");}

}

D:\psr\J2EE>javac Cone1.javaD:\psr\J2EE>javap Cone1Compiled from “Cone1.java”Public class Cone1 extends java.lang.object {

public Cone1(int );public void mone( );

}

When the above source file is compiled, the java compiler will not add a zero argument constructor on its own as we have provided one constructor on the source file.

extends extends

Person p;Student s; Student(obj)Teacher t; s s = new Student( ); (Student)

Student seen as Student Student(obj)

p = new Student( ); p (Student)

Student seen as Person

SUDHEER REDDY

2

Person

setName(String name)String getName( )

Student

setFee(float fee)float getFee( )

Teacher

setSal(float sal)float getSal( )

Page 3: J2EE Notes

POTHURAI

p,s,t are called as reference variables. A super class reference can refer (point to) a sub class object.Ex: - reference variable p (person type) can refer to student object & teacher object.

public class App {

public static void main(String[] args) {

Object o;o=new Cone( );String s=o.toString( );System.out.println(s);

}}

D:\psr\J2EE>javac App.javaD:\psr\J2EE>java AppCone@82ba41

public class Ctwo{

public void mone( ){

// System.out.println("------Ctwo:mone------");}public String toString( ){

System.out.println("-----Ctwo:toString( )-----");return "Sudheer";

}}

public class App {

public static void main(String[] args) {

Object o;o=new Ctwo( );/* String s=o.toString( );System.out.println(s); */System.out.println(o);

}}D:\psr\J2EE>javac App.javaD:\psr\J2EE>java App-----Ctwo:toString( )-----Sudheer

SUDHEER REDDY

3

Page 4: J2EE Notes

POTHURAI

extends

extends

ClsTwo is direct subclass of ClsOne. It is indirect subclass of Object.ClsOne is direct super class of ClsTwo. Object class is indirect super class of ClsTwo.

Object o = new ClsTwo( ); 1o.toString( ); 2System.out.println(o); 3

1 ClsTwo object will be created & it will be referenced by the variable o.2 When a method is invoked the JVM checks for the method in the based on which the object is created. In ClsTwo toString method is available. This is why the JVM executes the toString method of ClsTwo.3 When System.out.println is executed internally toString method will be executed.

In the above example “sunil” will be displayed.

Object o=new ClsOne( ); 1o.toSting( ); 2

1 ClsOne object will be created & referenced by o.2 JVM checks for toString method in ClsOne, as the method is not available in ClsOne, the JVM executes the toString method available in the object class.

public class Emp{

private int empno;private String empName;private float salary;public Emp(int empno,String empName,float salary){

this.empno=empno;

SUDHEER REDDY

4

java.lang.ObjectString toString( ) returns clsName@ hash code

ClsOne

toString( ) not found

ClsTwo

String toString( ) { return “Sunil”};

Page 5: J2EE Notes

POTHURAI

this.empName=EmpName;this.salary=salary;

}--------

}Emp c1=new Emp(1,"EOne",10000.001f);Emp c2=new Emp(2,"ETwo",20000.002f);

c1

Emp

c2

Emp

Emp obj is for holding details of an EmpStudent obj for holding details of a StudentClass obj is for holding details of Class.

java.lang.Class is a class & the objects based on this class are used & hold the details of a class.

Class cls1=Class.forName("java.lang.String");Class cls2=Class.forName("java.util.Date");

cls1

java.lang.Class

cls2

java.lang.Class

When a class Or an interface has to be used by the JVM the .class file will be read & the information will be loaded in to the JVM’S memory, this process is called as class loading.

public class Appli{

public static void main(String[] args) throws Exception{

SUDHEER REDDY

5

Info aboutString class

Info aboutDate class

1EOne

100000.001

2ETwo

200000.002

Page 6: J2EE Notes

POTHURAI

System.in.read( ); System.in.read( );Class cls1=Class.forName("java.util.Date");System.in.read( ); System.in.read( );Class cls2=Class.forName("java.util.Date");System.in.read( ); System.in.read( );

}}

D:\psr\J2EE> javac Appli.javaD:\psr\J2EE> java –verbose Appli

Class.forName method loads a class if it was not loaded earlier & returns on object of type class.

public class Application{

public static void main(String[] args) throws Exception{

Class cls=Class.forName("java.lang.String");System.out.println(cls.getName( ));System.out.println(cls.getPackage( ));

}}

D:\psr\J2EE>javac Appli.javaD:\psr\J2EE>java Applijava.lang.Stringpackage java.lang, java platform API specification, version 1.5 The above application always loads the same class (java.lang.String).

java -D spone = xyz –Dsptwo=abc Applications

value of the system property name of the system property

define a system property

public class Applications{

public static void main(String[] args) throws Exception{

String vspone=System.getProperty("spone");String vsptwo=System.getProperty("sptwo");System.out.println(vspone);System.out.println(vsptwo);

}}

SUDHEER REDDY

6

Page 7: J2EE Notes

POTHURAI

D:\psr\J2EE>javac Applications.javaD:\psr\J2EE>java ApplicationsnullnullD:\psr\J2EE>java -Dspone=xyz –Dsptwo=abc Applicationsxyzabc

public class AApplications{

public static void main(String[] args) throws Exception{

String vclsname=System.getProperty("clsname");System.out.println(vclsname);Class cls=Class.forName(vclsname);System.out.println(cls.getName( ));System.out.println(cls.getPackage( ));

}}

If we can run the above application using the following command java.net.Socket will be loaded.

The same application loads java.util.Vector if we use the following command.

D:\psr\J2EE>javac AApplications.javaD:\psr\J2EE>java –Dclsname=java.net.Socket AApplicationsjava.net.Socketjava.net.Socketpackage java.net, java platform API specification, version 1.5D:\psr\J2EE>java –Dclsname= java.util.Vector AApplicationsjava.util.Vector java.util.Vectorpackage java.util, java platform API specification, version 1.5

log4j API: -here j=java, 4=for, API=application programming interface.log4j can be used for writing the log messages to various kinds of definitions

like a file, database, console etc …Ex: - C:\bea\user-projects\domains\pothurai\myServer\myServer.log >startweblogic

It is always advisable to use some sort of logging API document to generate the log messages. The log messages helps the end user as well as the developer of the application, to know about what the application has done & why the application has failed etc…

log4j API is developed by apache (www.apache.org) & is used as part of various products like hibernate, struts, spring etc…

log4j-1.2.8.jar: - It contains the classes & interfaces that are part of log4j API.

SUDHEER REDDY

7

Page 8: J2EE Notes

POTHURAI

set CLASSPATH= . : ; C:\xyz; log4j-1.2.8.jar

Current directory Environment variable

Command in dosjavap org.apache.log4j.Appender

Name of the interface1) java related tools like javap, javac, JVM uses the environment variable

CLASSPATH to search for .class file.2) We can specify multiple directories & jar files has part of CLASSPATH

environment variable.Windows OS: -

set CLASSPATH= . : ; C:\xyz; log4j-1.2.8.jarLinux / UNIX OS: -

export set CLASSPATH= . :/USR/home: log4j-1.2.8.jar

There are various types of messages that can be generated by an application. Log4j supports the following types of log message.

1) debug 2) info 3) warn 4) error 5) fatal (very serious errors).

import org.apache.log4j.*;public class Log{

public static void main(String[] args) throws Exception{

Layout layout=new SimpleLayout( );Appender appender=new ConsoleAppender(layout);Logger logger=Logger.getRootLogger( );logger.addAppender(appender);logger.debug("--msg one -- ");logger.info("--msg two -- ");logger.warn("--msg three -- ");logger.error("--msg four -- ");logger.fatal("--msg five -- ");

}}

Layout formatted messages.

SimpleLayout

Adapter DEBUG - --msg one –

ConsoleAppender

Logger RootLogger

SUDHEER REDDY

8

Page 9: J2EE Notes

POTHURAI

D:\psr\J2EE> set CLASSPATH=.; log4j-1.2.8.jarD:\psr\J2EE>javac Log.javaD:\psr\J2EE>java LogDEBUG - --msg one -- INFO - --msg two -- WARN - --msg three -- ERROR - --msg four -- FATAL - --msg five –

import org.apache.log4j.*;public class Log4j{

public static void main(String[] args) throws Exception{

Layout layout=new SimpleLayout( );Appender appender1=new ConsoleAppender(layout);Appender appender2=new FileAppender (layout, "Log4j.log");Logger logger=Logger.getRootLogger( );logger.addAppender(appender1);logger.addAppender(appender2);logger.debug("--msg one -- ");logger.info("--msg two -- ");logger.warn("--msg three -- ");logger.error("--msg four -- ");logger.fatal("--msg five -- ");

}}

D:\psr\J2EE>javac Log4j.javaD:\psr\J2EE>java Log4jDEBUG - --msg one -- INFO - --msg two -- WARN - --msg three -- ERROR - --msg four -- FATAL - --msg five –

import org.apache.log4j.*;public class Log4j1{

public static void main(String[] args) throws Exception{

Layout layout=new HTMLLayout( );Appender appender1=new ConsoleAppender(layout);Appender appender2=new FileAppender(layout, "Log4j1.html");

Logger logger=Logger.getRootLogger( );logger.addAppender(appender1);

SUDHEER REDDY

9

Page 10: J2EE Notes

POTHURAI

logger.addAppender(appender2);logger.debug("--msg one -- ");logger.info("--msg two -- ");logger.warn("--msg three -- ");logger.error("--msg four -- ");logger.fatal("--msg five -- ");

}}

D:\psr\J2EE>javac Log4j1.javaD:\psr\J2EE>java Log4j1

Log session start time Mon Aug 27 12:45:32 IST 2007

Time Thread Level Category Message

0 main DEBUG root --msg one --

31 main INFO root --msg two --

47 main WARN root --msg three --

47 main ERROR root --msg four --

62 main FATAL root --msg five --

import org.apache.log4j.*;public class Log4j2{

public static void main(String[] args) throws Exception{

Layout layout=new SimpleLayout( );Appender appender=new ConsoleAppender(layout);Logger logger=Logger.getRootLogger( );logger.addAppender(appender);logger.setLevel(Level.WARN);logger.debug("--msg one -- ");logger.info("--msg two -- ");logger.warn("--msg three -- ");logger.error("--msg four -- ");logger.fatal("--msg five -- ");

}}

D:\psr\J2EE>javac Log4j2.javaD:\psr\J2EE>java Log4j2WARN - --msg three -- ERROR - --msg four --

SUDHEER REDDY

10

Page 11: J2EE Notes

POTHURAI

FATAL - --msg five – Debug is considered to be at the lowest level & fatal is consider being at the heights level. If we want to write error & fatal error messages then we must set the log level as shown below

logger.setLevel(Level.ERROR);

log4j properties: - log4j.rootCategory=ERROR, A1log4j.appender.A1=org.apache.log4j.ConsoleAppenderlog4j.appender.A1.layout=org.apache.log4j.SimpleLayout

import org.apache.log4j.*;public class Log4j3{

public static void main(String[] args) throws Exception{

PropertyConfigurator.configure("log4j.properties");Logger logger=Logger.getRootLogger( );logger.debug("--msg one -- ");logger.info("--msg two -- ");logger.warn("--msg three -- ");logger.error("--msg four -- ");logger.fatal("--msg five -- ");

}}

D:\psr\J2EE>javac Log4j3.javaD:\psr\J2EE>java Log4j3ERROR - --msg four -- FATAL - --msg five –

configure methods reads log4j properties file & decides about the appenders, layouts, log level. public class CThr{

public void mone( ){

System.out.println("---------CThr:mOne--------");}public CThr( ){

System.out.println("---CThr created---");}

}

D:\psr\J2EE>javac CThr.java

SUDHEER REDDY

11

Page 12: J2EE Notes

POTHURAI

public class CFour{

public void mone( ){

System.out.println("---------CFour:mOne--------");}

}

D:\psr\J2EE>javac CFour.java

public class CFive{

public void mone( ){

System.out.println("---------CFive:mOne--------");}public CFive(int i){

System.out.println("---CFive created---");}

}

D:\psr\J2EE>javac CFive.java

public class AApp{

public static void main(String args[]) throws Exception{

String vclsname=System.getProperty("clsname"); 1Class cls=Class.forName(vclsname); 2Object o=cls.newInstance( ); 3System.out.println("o-->"+o.getClass( ));

}}

1 CThr will be returned by System.getProperty(…) 2 When Class.forName is executed CThr class will be loaded (if it was not loaded earlier) & an object of type java.lang.Class will be returned. The object contains the information about CThr class.

Cls

java.lang.Class object

SUDHEER REDDY

12

Info aboutCThr class

Page 13: J2EE Notes

POTHURAI

3 When newInstance( ) method executed, it will create an object of type CThr using the zero argument constructor of CThr class.Note: - if there is no zero argument constructor in CThr in CThr.class then newInstance( ) method fails to create an object.

o

CThr object

The same application creates an objects of type Cxxx, if it is executed using the command as shown below

java -dclsname=Cxxx AApp

D:\psr\J2EE>javac AApp.javaD:\psr\J2EE>java –Dclsname= CThr AApp---CThr created---o-->class CThr

D:\psr\J2EE>java –Dclsname= CFour AAppo-->class CFour

D:\psr\J2EE>java –Dclsname= CFive AAppException in thread “main” java.lang.InstantiationException: CFive

at java.lang.Class.newInstance0(Unknown Source) at java.lang.Class.newInstance(Unknown Source) at AApp.main(AApp.java:7)

1 error

Because the CFive class is contain parameter argument constructor.

We can develop the flexible java applications by using the interfaces.

(I mean) Prefix of interface

implements implements

SUDHEER REDDY

13

IBillCalculator

float calcBill(String cid,int nocu);

Student

ATBillCalculator

public float calcBill(…) {code to calc bill acc the policies

of AIRTEL }

HBillCalculator

public float calcBill(…) {code to calc bill acc the policies of HUTCH }

NTBC

Page 14: J2EE Notes

POTHURAI

public interface IBillCalculator{

float calcBill(String cid,int nocu);}

D:\psr\J2EE>javac IBillCalculator.java

A reference variable of type interface can refer to an object that is based on a class that implements the interface.

IBillCalculator bc; bc=new ATBillCalculator( ); bc=new Student( ); X // because it is not implemented.

public class Student {}

D:\psr\J2EE>javac Student.java

public class TBApp{

public static void main(String args[]) throws Exception{

String vclsname=System.getProperty("clsname");Class cls=Class.forName(vclsname);Object o=cls.newInstance( );IBillCalculator bc;bc=(IBillCalculator)o;

}}

D:\psr\J2EE>javac TBApp.javaD:\psr\J2EE>java –Dclsname=Student TBAppException in thread “main” java.lang.ClassCastException: Student

at TBApp.main(TBApp.java:9)1 error

public class ATBillCalculator implements IBillCalculator{

public float calcBill(String cid,int nocu){

// code to calculate bill all to airtelSystem.out.println("----AIRTEL----");float billAmt=100;int utc=nocu-200;

SUDHEER REDDY

14

Page 15: J2EE Notes

POTHURAI

if(utc>0){

billAmt+=(utc*1);}return billAmt;

}}

The code in the method calcBill is implemented according to the policies.D:\psr\J2EE>javac ATBillCalculator.java

public class TBApp{

public static void main(String args[]) throws Exception{

String vclsname=System.getProperty("clsname");Class cls=Class.forName(vclsname);Object o=cls.newInstance( ); 1IBillCalculator bc;bc=(IBillCalculator)o; 2System.out.println("------tc successful------");float ba=bc.calcBill("xyz",400); 3System.out.println("Bill Amount-->"+ba);

}}

D:\psr\J2EE>javac TBApp.java

1 An object of type ATBillCalculator will be created & it will be referred by the variable o. 2 Type casting will be performed & ATBillCalculator object will be referred by the variable bc.

o bc

ATBillCalculator object 3 When calcBill is called the JVM executes the calcBill method of ATBillCalculator.

The above application is very flexible. We can make this application work for HUTCH without disturbing the existing code.

D:\psr\J2EE>java –Dclsname= ATBillCalculator TBApp------tc successful----------AIRTEL----Bill Amount-->300.0

public class HBillCalculator implements IBillCalculator{

SUDHEER REDDY

15

Page 16: J2EE Notes

POTHURAI

public float calcBill(String cid,int nocu){

// code to caluclate bill all to airtelSystem.out.println("----HUTCH----");float billAmt=100;int utc=nocu-225;if(utc>0){

billAmt+=(utc*1.25);}return billAmt;

}}

D:\psr\J2EE>javac HBillCalculator.javaTBApp can be used to calculate the bills for HUTCH by starting the

application using the command as shown below

D:\psr\J2EE>java –Dclsname= HBillCalculator TBApp------tc successful---------- HUTCH ----Bill Amount-->318.75

The above application exhibits multiple behaviors (polymorphic). It works where any class provides the implementation of IBillCalculator interface.

public class NTBC implements IBillCalculator{

public float calcBill(String cid,int nocu){

// code to caluclate bill all to NTBCSystem.out.println("----NT----");float billAmt=0;billAmt+=nocu * 0.75;return billAmt;

}}

D:\psr\J2EE>javac NTBC.javaD:\psr\J2EE>java –Dclsname=NTBC TBApp------tc successful---------- NT ----Bill Amount-->300.0

The above application can work with any class that implements IBillCalculator & these classes need not be provided by the company that has develop the interface.

SUDHEER REDDY

16

Page 17: J2EE Notes

POTHURAI

1) We can declare a reference variable of type interface, but we can not create an object based on interface.

IBillCalculator bc; IBillCalculator bc=new IBillCalculator( ); X

2) Once an interface is provided by a company, any number of classes can be provided implementing the same interface & these classes can be provided by any company.3) If the application uses a reference variable of type interface & if the objects are created dynamically (using newInstance( ) method) then we make the application flexible.

The technique shown in TBApp is used heavily in the design of several API’S, products / projects. For a java developer an API is a set of classes & interface, that the design for a specific purpose.

JDBC API: - (Java Database connectivity) -- Used to deal with database servers.Java Mail API: - Used to send & receive mails from a java application.Java TAPI: - Java Telephonic application programming interface.J2sdk: - Java software development kit.

Java soft has designed various API’S.A set of API’S like jdbc, jndi, AWT/WING, networking API etc… are part of java standard edition. JEE is a combination of API’S like java mail API, servlet API, EJB, JMS etc…

JDBC API is a part of java standard edition. We can use JDBC to access the databases like Oracle, Micro Soft SQL server, MySql server, SyBase, Ingress, DB2 --- etc…

A java application must establish the connection with the database to use /talk with the database server.

Oracle server Java App

Ojdbc14 provided by Oracle Corporation. (www.oracle.com)This files contains is a set of classes that are implemented by Oracle corporation.

import java.sql.*;public class Jdbc{

public static void main(String[] args) throws Exception{

SUDHEER REDDY

17

ip—196.12.100.1port—1521

service name—xeConnection object

Page 18: J2EE Notes

POTHURAI

Connection con;con=new oracleDriver( );System.out.println(“------Connected------”);

}}D:\psr\J2EE>javac Jdbc.javaD:\psr\J2EE>java JdbcJdbc.java:7: cannot find symbolsymbol : class oracleDriverlocation: class Jdbc con=new oracleDriver( ); ^1 errorD:\psr\J2EE> set CLASSPATH=ojdbc14.jar;.D:\psr\J2EE>java Jdbc-----Connected------

SUDHEER REDDY

18

java.sql.Connectionprovide java soft

oracle.jdbc.oracleConnetionprovided by Oracle

oracle.jdbc.internal.Connetionprovided by Oracle

oracle.jdbc.driver.oracleDriverprovided by Oracle

java.sql.Driverprovide java soft

oracle.jdbc.driver.oracleDriverprovided by Oracle

Page 19: J2EE Notes

POTHURAI

As part of JDBC API, java soft has provided several interfaces like java.sql.Driver, Connection, ResultSet, Statement, CalledStatement, preparedStatement etc …Driver class: - A class that provides the implementation of java.sql.Driver interface.mysql-Connector-java-3.0.11-stable.tar.gz-----(www.mysql.com)It provided by MySql AB.Ex: - com.mysql.jdbc.Driver is a Driver class provided by MySql AB

mysql-Connector-java-3.0.11-stable.bin.jar.

JDBC Driver: - it is a set of classes provides the implementation of the interfaces, that or are part of JDBC API.Ex: - ojdbc14.jar, mysql-Connector-java-3.0.11-stable.bin.jar contains the classes that implements JDBC related interfaces.

In order to establish the connection the name of the driver class & the format of JDBC URL is required. For this information we can refer to the manual / documentation provided by the Vendor of the JDBC driver.

import java.sql.*;public class OraApp{

public static void main(String[] args) throws Exception{

Driver drv=new oracle.jdbc.driver.OracleDriver( );DriverManager.registerDriver(drv);Connection con=DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:xe","system","sunil");System.out.println("--- Connected -->"+con.getClass( ));

}}

D:\psr\J2EE>javac OraApp.javaD:\psr\J2EE>java OraApp--- Connected -->class oracle.jdbc.driver.T4CConnection

import java.sql.*;public class MyApp{

public static void main(String[] args) throws Exception{

SUDHEER REDDY

19

java.sql.Driver--- Connection--- StatementInterfaces provided by java soft

Classes implementing the interface of JDBC API provided by oracle corp.

Page 20: J2EE Notes

POTHURAI

Driver drv=new com.mysql.jdbc.Driver( );DriverManager.registerDriver(drv);Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test"," "," ");System.out.println("--- Connected -->"+con.getClass( ));

}}

* How to register a Driver?: - 1) We can register the driver using DriverManager.registerDriver.Ex: - Driver drv=new oracle.jdbc.driver.OracleDriver( );

DriverManager.registerDriver(drv); 2) When a class is loaded the static block available in the class will be executed by the JVM.Ex: - public class XDrv{

static{

System.out.println("------XDrv executed------");}

}D:\psr\J2EE>javac XDrv.java

public class Xdrv1{

public static void main(String[] args) throws Exception{

Class.forName("XDrv");}

}D:\psr\J2EE>javac Xdrv1.javaD:\psr\J2EE>java Xdrv1------XDrv executed------

3) As a part of the driver classes the jdbc driver vendor provides a static block. As a part of static block of a driver class code will be provided for registering the driver.Ex: - public class OracleDriver ------

{Static{Driver drv=new oracle.jdbc.driver.OracleDriver( );DriverManager.registerDriver(drv);}

}

SUDHEER REDDY

20

Page 21: J2EE Notes

POTHURAI

4) When forName is executed the driver class will be loaded, by JVM executes the static class of the driver class. The code of the static block of the driver class registers the driver.Ex: - Class.forName("oracle.jdbc.driver.OracleDriver ");* How can your application create a connection object?: - 1) Every jdbc driver vendor provides a class implementing java.sql.Connection interface (ex: - oracle.jdbc.driver.OracleConnection , com.mysql.Connection are the classes that implements connection interface). 2) When the application class DriverManager.getConnection, internally it will call the connect method available in the Driver class provide by the driver vendor.

The code provide by the vendor in the connect method of driver Class establishes the connection of a server & creates an object based on a class that is provided by the vendor implementing java.sql.Connection interface.

Oracle server Java DBApp (client)

import java.sql.*;public class DBApp{

public static void main(String args[]) throws Exception{

Class.forName("oracle.jdbc.driver.OracleDriver");Connection con=DriverManager.getConnection

("jdbc:oracle:thin:@localhost:1521:xe","system","sunil");Statement stmt=con.createStatement( );String vsql="create table employee (empname varchar(10), empno number(3),salary number(10,2))";stmt.executeUpdate(vsql);

}}

D:\psr\J2EE>javac DBApp.javaD:\psr\J2EE>java DBAppSQL> desc employee; Name Null? Type ----------------------------------------- -------- ---------------------------- EMPNAME VARCHAR2(10) EMPNO NUMBER(3) SALARY NUMBER(10,2)

SUDHEER REDDY

21

Create …..

Connection

Statement

Page 22: J2EE Notes

POTHURAI

When stmt.executeUpdate(vsql); is called by our java application the following steps will be carried out:

1) The JDBC driver sends the SQL statement to the database server.2) The database server splits the SQL statement into multiple pieces to analyze

whether the statement is valid or not. This is called ‘PARSING’3) a) if the statement is not valid the server sends the error to the client & the

JDBC driver throws java.sql.SqlException.b) if the statement is valid the server executes the statement (the server carries out the appropriate task requested by the SQL statement).

insert into employee values (‘EOne’,1,10000)insert into employee values (‘ETwo,2,20000)….….insert into employee values (‘Exyz’,3,11111)

When the user uses the above application he will fill the details of several employee (200) & the application has to repeated by execute the same insert statement with a difference set of values.

When stmt.executeUpdate is called repeatedly (200 times), the jdbc driver sends the sql statements for 200 times to the server. The server performs parsing for 200 times & carries out the execution for 200 times.

SQL> select * from employee;no rows selectedSQL> commit;Commit complete.

import java.sql.*;public class SDBApp{

public static void main(String args[]) throws Exception{

Class.forName("oracle.jdbc.driver.OracleDriver");

SUDHEER REDDY

22

Empname:

Empno:

Salary:

EOne

1

10000

Store emp

Page 23: J2EE Notes

POTHURAI

Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","sunil");// code to connect to DBStatement stmt=con.createStatement( );String vsql1="insert into employee values (1,'EOne',10000)";String vsql2="insert into employee values (2,'ETwo',20000)";String vsql200="insert into employee values (200,'EXyz',11111)";stmt.executeUpdate(vsql1);stmt.executeUpdate(vsql2);stmt.executeUpdate(vsql200);

}}

D:\psr\J2EE>javac SDBApp.javaD:\psr\J2EE>java SDBAppSQL> select * from employee;EMPNAME EMPNO SALARY---------- ---------- --------------------- -------------EOne 1 10000ETwo 2 20000EXyz 200 11111

The above application is repeatedly executing the “same statement with a different set of values”. We can improve the performance of these kinds of applications using PreparedStatement object instead of a statement object.

As a part of SQL statements we must use the question mark (?) as shown below without providing the values. These question marks are called as parameters / place holders / bind variables.

ParametersPlace holders bind variables

insert into employee values ( ? , ? , ? );

para1, para2, para3

import java.sql.*;public class PSDBApp{

public static void main(String args[]) throws Exception{

Class.forName("oracle.jdbc.driver.OracleDriver");Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","sunil");// code to connect to DBString vsql="insert into employee values(?,?,?)";PreparedStatement pstmt=con. prepareStatement(vsql);pstmt.setString(1,"EOne");

SUDHEER REDDY

23

Page 24: J2EE Notes

POTHURAI

pstmt.setInt(2,1);pstmt.setFloat(3,10000);pstmt.executeUpdate( );pstmt.setString(1,"ETwo");pstmt.setInt(2,2);pstmt.setFloat(3,20000);pstmt.executeUpdate( );pstmt.setString(1,"EXyz");pstmt.setInt(2,200);pstmt.setFloat(3,11111);pstmt.executeUpdate( );

}}

D:\psr\J2EE>javac PSDBApp.javaD:\psr\J2EE>java PSDBAppSQL> select * from employee;EMPNAME EMPNO SALARY---------- ---------- --------------------- -------------EOne 1 10000ETwo 2 20000EXyz 200 11111

The JDBC driver sends the SQL statement to the server. The server parses the statement & the driver provides the values to the server. The server executes the statement using the values. The driver provides the values of the parameters to the server. The server executes the statement which was parsed earlier using the values provided by the driver.

In this case parsing is carried out only once, where as in case of the statement objects parsing is carried out from 200 times. By reducing the number of parses, the performance of application will be improved.

import java.sql.*;public class DDBApp{

public static void main(String args[]) throws Exception{

Class.forName("oracle.jdbc.driver.OracleDriver");Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","sunil");// code to connect to DBString vsql="delete from employee where empno=?";PreparedStatement pstmt=con.prepareStatement(vsql);pstmt.setInt(1,1);pstmt.executeUpdate( );pstmt.setInt(1,2);pstmt.executeUpdate( );

SUDHEER REDDY

24

Page 25: J2EE Notes

POTHURAI

pstmt.setInt(1,200);pstmt.executeUpdate( );

}}D:\psr\J2EE>javac DDBApp.javaD:\psr\J2EE>java DDBAppSQL> select * from employee;no rows selected

We can use PreparedStatement to execute the Update statement, select statement also.Update employee set salary=60000 where empno=200;Update employee set salary=50000 where empno=2;Update employee set salary=40000 where empno=1;

SQL> insert into employee values ('EOne',1,1);1 row created.SQL> insert into employee values ('ETwo',2,2);1 row created.SQL> insert into employee values ('EXyz',200,10000);1 row created.SQL> select * from employee;EMPNAME EMPNO SALARY---------- ---------- ----------------- --------------ETwo 2 2EXyz 200 10000EOne 1 1SQL> commit;Commit complete. import java.sql.*;public class StDBApp{

public static void main(String args[]) throws Exception{

Class.forName("oracle.jdbc.driver.OracleDriver");Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","sunil");// code to connect to DBString vsql="update employee set salary=? where empno=?";PreparedStatement pstmt=con.prepareStatement(vsql);pstmt.setString(1,"60000");pstmt.setString(2,"200");pstmt.executeUpdate( );pstmt.setString(1,"50000");pstmt.setString(2,"2");pstmt.executeUpdate( );pstmt.setString(1,"40000");

SUDHEER REDDY

25

Page 26: J2EE Notes

POTHURAI

pstmt.setString(2,"1");pstmt.executeUpdate( );;

}}D:\psr\J2EE>javac StDBApp.javaD:\psr\J2EE>java StDBAppSQL> select * from employee;EMPNAME EMPNO SALARY---------- ---------- ----------- ------------------ETwo 2 50000EXyz 200 60000EOne 1 40000

* What is the difference between executeUpdate & executeQuery? : - executeQuery is for executing a select statement, the return type of

executeQuery method is ResultSet.executeUpdate method is for executing non select statement & the return

type of executeUpdate is int. The return type of executeUpdate indicates the number of rows affected.

delete from employeeEx:- import java.sql.*;public class DeDBApp{

public static void main(String args[]) throws Exception{

Class.forName("oracle.jdbc.driver.OracleDriver");Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","sunil");Statement stmt=con.createStatement( );String vsql="delete from employee";int nore=stmt.executeUpdate(vsql);System.out.println("------nore----->"+nore);

}}

D:\psr\J2EE>javac DeDBApp.javaD:\psr\J2EE>java DeDBApp------nore----->3SQL> select * from employee;no rows selected

if 10 rows in there in the data base & 10 rows will be deleted & a return value 10 will be given by executeUpdate, but it be use “drop table employee”, executeUpdate returns 0.

SUDHEER REDDY

26

Page 27: J2EE Notes

POTHURAI

import java.sql.*;public class DeDBApp{

public static void main(String args[]) throws Exception{

Class.forName("oracle.jdbc.driver.OracleDriver");Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","sunil");Statement stmt=con.createStatement( );String vsql=" drop table employee”;int nore=stmt.executeUpdate(vsql);System.out.println("------nore----->"+nore);

}}

D:\psr\J2EE>javac DeDBApp.javaD:\psr\J2EE>java DeDBApp------nore----->0SQL> select * from employee;select * from employee *ERROR at line 1:ORA-00942: table or view does not exist

SQL> select * from employee; EMPNO ENAME SALARY---------- ---------- ---------- ------------------ 1 EOne 10000 2 ETwo 20000 3 EThr 30000

import java.sql.*;public class RSDBApp{

public static void main(String args[]) throws Exception{

Class.forName("oracle.jdbc.driver.OracleDriver");Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","sunil");Statement stmt=con.createStatement( );String vsql="select * from employee";ResultSet rs=stmt.executeQuery(vsql);System.out.println("--cur row -->"+rs.getRow( ));rs.next( );System.out.println(rs.getRow( ));rs.next( );System.out.println(rs.getRow( ));

SUDHEER REDDY

27

Page 28: J2EE Notes

POTHURAI

rs.next( );System.out.println(rs.getRow( ));rs.next( );System.out.println(rs.getRow( ));rs.next( );

}}D:\psr\J2EE>javac RSDBApp.javaD:\psr\J2EE>java RSDBApp--cur row -->01230

ResultSet object can be used to access the data that is returned by the data base server. When the ResultSet is opened, it will be pointing to before first row. rs.next( )moves the Resultset current row pointer to the next available row. This method returns false, when it points to after last row.

Java DBAppDatabase

import java.sql.*;public class RSDBApp{

public static void main(String args[]) throws Exception{

Class.forName("oracle.jdbc.driver.OracleDriver");Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","sunil");Statement stmt=con.createStatement( );String vsql="select * from employee";ResultSet rs=stmt.executeQuery(vsql);while(rs.next( )){

System.out.println("--cur row -->”+rs.getRow( ));System.out.println(rs.getInt("empno"));System.out.println(rs.getString("ename"));System.out.println(rs.getFloat("salary"));

SUDHEER REDDY

28

Employee

ResultSet

empno….

Page 29: J2EE Notes

POTHURAI

System.in.read( ); System.in.read( );}

}}D:\psr\J2EE>javac RSDBApp.javaD:\psr\J2EE>java RSDBApp--cur row -->11EOne10000.0--cur row -->22ETwo20000.0--cur row -->33EThr30000.0

By default read only, forward only ResultSet will be created. Forward only ResultSet allows next method (that is we can move only in the forward direction.). We can not use the methods previous, first, last & absolute on forward only ResultSet.

Scrollable ResultSet allows an application to move in both the directions. We can use next, previous, first, last, absolute methods on scrollable ResultSet. There are 2 types of scrollable ResultSets.

1) Scroll Sensitive ResultSet : - We can use the method refreshRow( ) & get the fresh data (if the data is modified, it will get the modified data).

2) Scroll InSensitive ResultSet : - The ResultSet is not sensitive to the changes made by another client. That is we can not get the fresh data using refreshRow( ) method.

import java.sql.*;public class RSSDBApp{

public static void main(String args[]) throws Exception{

Class.forName("oracle.jdbc.driver.OracleDriver");Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","sunil");Statement stmt=con.createStatement(ResultSet.TYPE_

SCORLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);String vsql="select empno,ename,salary from employee";ResultSet rs=stmt.executeQuery(vsql);System.out.println("--about read 3rd row--");System.in.read( ); System.in.read( );rs.absolute(3);rs.refreshRow( );System.out.println(rs.getInt("empno"));

SUDHEER REDDY

29

Page 30: J2EE Notes

POTHURAI

System.out.println(rs.getString("ename"));System.out.println(rs.getFloat("salary"));

}}D:\psr\J2EE>javac RSSDBApp.javaD:\psr\J2EE>java RSSDBApp--about read 3rd row--3EThr30000.0

We can not insert, update and delete the data using READ_ONLY ResultSet (only read operation is permitted on read only ResultSet).

import java.sql.*;public class RSUDBApp{

public static void main(String args[]) throws Exception{

Class.forName("oracle.jdbc.driver.OracleDriver");Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","sunil");Statement stmt=con.createStatement(ResultSet.TYPE_

SCORLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);String vsql="select empno,ename,salary from employee";ResultSet rs=stmt.executeQuery(vsql);rs.absolute(3);rs.updateString("ename","NEThr");rs.updateString("salary","45000");rs.updateRow( );

}}

D:\psr\J2EE>javac RSUDBApp.javaD:\psr\J2EE>java RSUDBAppSQL> select * from employee2; EMPNO ENAME SALARY---------- ---------- ---------- ----------------- 1 EOne 10000 2 ETwo 20000 3 NEThr 45000

When rs.updateXxx( )method is used, the data will be modified in the ResultSet. To apply these changes to the database rs.updateRow( ) must be used.

To delete the fourth row we can use the code as shown below.

SUDHEER REDDY

30

Page 31: J2EE Notes

POTHURAI

import java.sql.*;public class RSDDBApp{

public static void main(String args[]) throws Exception{

Class.forName("oracle.jdbc.driver.OracleDriver");Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","sunil");Statement stmt=con.createStatement(ResultSet.TYPE_

SCORLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);String vsql="select empno,ename,salary from employee";ResultSet rs=stmt.executeQuery(vsql);rs.absolute(3);rs.updateString("ename","Sunil");rs.updateString("salary","25000");rs.updateRow( );rs.absolute(2);rs.deleteRow( );

}}

D:\psr\J2EE>javac RSDDBApp.javaD:\psr\J2EE>java RSDDBAppSQL> select * from employee2; EMPNO ENAME SALARY---------- ---------- ---------- -------------------- 1 EOne 10000 3 Sunil 25000

To insert the row we can use the code as shown below.

import java.sql.*;public class RSIDBApp{

public static void main(String args[]) throws Exception{

Class.forName("oracle.jdbc.driver.OracleDriver");Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","sunil");Statement stmt=con.createStatement(ResultSet.TYPE_

SCORLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);String vsql="select empno,ename,salary from employee";ResultSet rs=stmt.executeQuery(vsql);rs.moveToInsertRow( );rs.updateString("empno","100");rs.updateString("ename","NewEmp");rs.updateString("salary","12345");

SUDHEER REDDY

31

Page 32: J2EE Notes

POTHURAI

rs.insertRow( );}

}

D:\psr\J2EE>javac RSIDBApp.javaD:\psr\J2EE>java RSIDBAppSQL> select * from employee2; EMPNO ENAME SALARY---------- ---------- ---------- -------------------- 1 EOne 10000 3 Sunil 25000 100 Sudheer 12345

Employee

Empaddress

Transactions: - insert into employee values (100,‘Sunil’,12345);insert into empaddrs values (100,‘Stone’,‘cone’,‘sone’);insert into empaddrs values (100,‘Sttwo’,‘ctwo’,‘stwo’);

SUDHEER REDDY

32

empno ename salary

empno street city state

Employeeempno: ename:

salary: Addresses

street city state

100

12345

Sunil

stone

sttwo

cone

ctwo stwop

sone

Store

Page 33: J2EE Notes

POTHURAI

When the user (shown above) feeds the data & clicks on the store button, the application has to do some work (person transaction).

In the above application the following 3 statements must be executed as part of the transaction.Note: - In majority of classes a business application must execute multiple SQL statements as part of a transaction.

If the application executes all the statements in a transaction without any problem then the transaction should be consider as successful otherwise the transaction should be consider as a failure.

By default the JDBC driver uses “auto commit mode”. In auto commit mode, the JDBC driver commits a transaction after executing every sql statements.

If an application has to control the transaction then the auto commit must be set to false.

con.setAutoCommit(false);When auto commit is set to false, the JDBC driver will not commit a transaction after executing the SQL statement. In this case the application is responsible for using con.commit( ) to commit the transaction.con.rollback( ) to roll back the transaction.

Committing or rolling back a transaction ends transaction. A new transaction will be started in one of the following cases

1) When a connection is establish, the transaction is started.2) When the current transaction is ended.3) A new transaction will be started.

SQL> create table employee (eno number(4) primary key,ename varchar(10),salary number(10,2));Table created.SQL> create table empaddrs (eno number(4), street varchar(10), city varchar(10),state varchar(10));Table created.SQL> select * from employee;no rows selectedSQL> select * from empaddrs;no rows selected

import java.sql.*;public class TDBApp{

public static void main(String args[]) throws Exception{

Class.forName("oracle.jdbc.driver.OracleDriver");Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","sunil");Statement stmt=con.createStatement( );String vsql1="insert into employee values (100,'Sunil',12345)";String vsql2="insert into empaddrs values (100,'stone','cone','sone')";String vsql3="insert into empaddrs values(100,'sttwo','ctwo','stwo')";

SUDHEER REDDY

33

Page 34: J2EE Notes

POTHURAI

con.setAutoCommit(false);try{

stmt.executeUpdate(vsql1);System.out.println("--executed-->"+vsql1);System.in.read( ); System.in.read( );stmt.executeUpdate(vsql2);System.out.println("--executed-->"+vsql2);System.in.read( ); System.in.read( );stmt.executeUpdate(vsql3);System.out.println("--executed-->"+vsql3);System.in.read( ); System.in.read( );con.commit( );

}catch (Exception e){

con.rollback( );}

}}

D:\psr\J2EE>javac TDBApp.javaD:\psr\J2EE>java TDBApp--executed-->insert into employee values(100,'Sunil',12345)--executed-->insert into empaddrs values(100,'stone','cone','sone')--executed-->insert into empaddrs values(100,'sttwo','ctwo','stwo')

SQL> select * from employee; ENO ENAME SALARY---------- ---------- ---------- ----------------- 100 Sunil 12345SQL> select * from empaddrs; ENO STREET CITY STATE---------- ---------- ---------- ---------- ------------ 100 stone cone sone 100 sttwo ctwo stwo

Batch updates improves the performance of the applications. A group of statements is called as a batch of statements.

import java.sql.*;public class TADBApp{

public static void main(String args[]) throws Exception{

Class.forName("oracle.jdbc.driver.OracleDriver");Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","sunil");Statement stmt=con.createStatement( );

SUDHEER REDDY

34

Page 35: J2EE Notes

POTHURAI

String vsql1="insert into employee values(101,'Sudheer',12346)";String vsql2="insert into empaddrs values(101,'stone','cone','sone')";String vsql3="insert into empaddrs values(101,'sttwo','ctwo','stwo')";con.setAutoCommit(false);try{

stmt.clearBatch( );stmt.addBatch(vsql1);stmt.addBatch(vsql2);stmt.addBatch(vsql3);stmt.executeBatch( );con.commit( );

}catch (Exception e){

con.rollback( );}

}}

D:\psr\J2EE>javac TADBApp.javaD:\psr\J2EE>java TADBAppSQL> select * from employee; ENO ENAME SALARY---------- ---------- ---------- ------------ 100 Sunil 12345 101 Sudheer 12346SQL> select * from empaddrs; ENO STREET CITY STATE---------- ---------- ---------- ---------- ----------------- 100 stone cone sone 100 sttwo ctwo stwo 101 stone cone sone 101 sttwo ctwo stwo

Data base Java App

SUDHEER REDDY

35

tax rates

spcalcx……..

min max tr

name

tot inc

name

1,50,000

Clac tax

Page 36: J2EE Notes

POTHURAI

Most of the database servers support the stored procedures. Sp’s improves the performance of the application & are used for the implementation to call a stored procedure. We can use CallableStatement to call a stored procedure.

create or replace PROCEDURE ProcOneas

i number;BEGIN data type

i:=44+11;insert into mytab values (100,i);

END ProcOne;/

SQL> @ d:\psr\sql\CreProc1.sql;Procedure createdSQL> create table mytab (COne number , CTwo number);Table created.SQL> desc mytab; Name Null? Type ----------------------------------------- -------- -------- CONE NUMBER CTWO NUMBERSQL> select * from mytab;no rows selected

We can use the code shown below to invoke proc1import java.sql.*;public class P1Sql{

public static void main(String args[]) throws Exception{

Class.forName("oracle.jdbc.driver.OracleDriver");Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","sunil");CallableStatement cstmt=con.prepareCall("{call ProcOne}");cstmt.execute( );

}}D:\psr\J2EE>javac P1Sql.javaD:\psr\J2EE>java P1SqlSQL> select * from mytab; CONE CTWO------------------- ---------- 100 55

create or replace PROCEDURE ProcTwo(pone IN number,ptwo IN number) as

SUDHEER REDDY

36

Page 37: J2EE Notes

POTHURAI

BEGINinsert into mytab values (pone,ptwo);

END ProcTwo;/SQL> @ d:\psr\sql\CreProc2.sql;Procedure createdSQL> delete mytab;1 row deleted.SQL> select * from mytab;no rows selected

import java.sql.*;public class P2Sql{

public static void main(String args[]) throws Exception{

Class.forName("oracle.jdbc.driver.OracleDriver");Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","sunil");CallableStatement cstmt=con.prepareCall("{call ProcTwo(?,?)}");cstmt.setInt(1,100);cstmt.setInt(2,200);cstmt.execute( );

}}

D:\psr\J2EE>javac P2Sql.javaD:\psr\J2EE>java P2SqlSQL> select * from mytab; CONE CTWO------------------- ---------- 100 200

create or replace PROCEDURE ProcThr(pa IN number,pb IN number,pc out number) asBEGIN

pc:=pa+pb;END ProcThr;/

SQL> @ d:\psr\sql\CreProc3.sql;Procedure created

import java.sql.*;public class P3Sql{

public static void main(String args[]) throws Exception

SUDHEER REDDY

37

Page 38: J2EE Notes

POTHURAI

{Class.forName("oracle.jdbc.driver.OracleDriver");Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","sunil");CallableStatement cstmt=con.prepareCall("{call ProcThr(?,?,?)}");cstmt.setInt(1,10);cstmt.setInt(2,20);cstmt.registerOutParameter(3,Types.INTEGER);cstmt.execute( );int res=cstmt.getInt(3);System.out.println("res----->"+res);

}}D:\psr\J2EE>javac P3Sql.javaD:\psr\J2EE>java P3Sqlres----->30 create or replace PROCEDURE ProcFour(pa IN OUT number,pb IN OUT number,pc out number) asBEGIN

pa:=pa+100;pb:=pb+200;pc:=pa+pb;

END ProcFour;/SQL> @ d:\psr\sql\CreProc4.sql;Procedure created import java.sql.*;public class P4Sql{

public static void main(String args[]) throws Exception{

Class.forName("oracle.jdbc.driver.OracleDriver");Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","sunil");CallableStatement cstmt=con.prepareCall("{call ProcFour(?,?,?)}");cstmt.setInt(1,10);cstmt.setInt(2,20);cstmt.registerOutParameter(1,Types.INTEGER);cstmt.registerOutParameter(2,Types.INTEGER);cstmt.registerOutParameter(3,Types.INTEGER);cstmt.execute( );System.out.println(cstmt.getInt(1));System.out.println(cstmt.getInt(2));System.out.println(cstmt.getInt(3));

}}D:\psr\J2EE>javac P3Sql.java

SUDHEER REDDY

38

Page 39: J2EE Notes

POTHURAI

D:\psr\J2EE>java P3Sql110220330 create or replace function myfunc(a number,b number) return numberasBEGIN

return a+b;END myfunc;/SQL> @d:\psr\sql\CreFunc.sql;Function created.

import java.sql.*;public class Func{

public static void main(String args[]) throws Exception{

Class.forName("oracle.jdbc.driver.OracleDriver");Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","sunil");CallableStatement cstmt=con.prepareCall("{?=call myfunc(?,?)}");cstmt.setInt(2,100);cstmt.setInt(3,200); cstmt.registerOutParameter(1,Types.INTEGER);cstmt.execute( );System.out.println(cstmt.getInt(1));

}}D:\psr\J2EE>javac Func.javaD:\psr\J2EE>java Func300

java.sql.Types: - It is a class. As part of this class, a set of constants like BEGIN, FLOAT, DOUBLE, NUMERIC, CHAR, VARCHAR, LONGVARCHAR etc… These constants represent various data types that are defined as part of sql standard.

import java.sql.*;public class Constants{

public static void main(String[] args) throws Exception{

System.out.println("NMERIC--->"+Types.NUMERIC);System.out.println("CHAR--->"+Types.CHAR);System.out.println("VARCHAR--->"+Types.VARCHAR);

SUDHEER REDDY

39

Page 40: J2EE Notes

POTHURAI

System.out.println("DATE--->"+Types.DATE);System.out.println("TSTAMP--->"+Types.TIMESTAMP);

}}D:\psr\J2EE>javac Constants.javaD:\psr\J2EE>java ConstantsNMERIC--->2CHAR--->1VARCHAR--->12DATE--->91TSTAMP--->93

ResultSetMetaData provides the information like no of columns that are fetched using the select statement, names of the columns, data type of the columns, size of the columns etc….

DatabaseMetaData provides the information about the jdbc driver & the database server.

SQL> create table test (COne char, CTwo varchar(10), CThr numeric);Table created.SQL> desc test; Name Null? Type ----------------------------------------- -------- ----------------- CONE CHAR(1) CTWO VARCHAR2(10) CTHR NUMBER(38)

import java.sql.*;public class ConstantsApp{

public static void main(String args[]) throws Exception{

Class.forName("oracle.jdbc.driver.OracleDriver");Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","sunil");Statement stmt=con.createStatement( );String vsql="select * from test";ResultSet rs=stmt.executeQuery(vsql);ResultSetMetaData rsmd=rs.getMetaData( );int noc=rsmd.getColumnCount( );System.out.println("noc--->"+noc);for(int i=1;i<=noc;i++){

System.out.print(rsmd.getColumnName(i)+"\t");System.out.println(rsmd.getColumnType(i));

}}

SUDHEER REDDY

40

Page 41: J2EE Notes

POTHURAI

}

D:\psr\J2EE>javac ConstantsApp.javaD:\psr\J2EE>java ConstantsAppnoc--->3CONE 1CTWO 12CTHR 2

import java.sql.*;public class ConstantsApp1{

public static void main(String args[]) throws Exception{

Class.forName("oracle.jdbc.driver.OracleDriver");Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","sunil");Statement stmt=con.createStatement( );String vsql="select * from test";ResultSet rs=stmt.executeQuery(vsql);ResultSetMetaData rsmd=rs.getMetaData( );int noc=rsmd.getColumnCount( );System.out.println("noc--->"+noc);for(int i=1;i<=noc;i++){

System.out.print(rsmd.getColumnName(i)+"\t");switch(rsmd.getColumnType(i)){

case Types.VARCHAR:System.out.println("VARCHAR");break;

case Types.CHAR:System.out.println("CHAR");break;

case Types.NUMERIC:System.out.println("NUMERIC");break;

default:System.out.println("Unknown");

}}

}}

D:\psr\J2EE>javac ConstantsApp1.javaD:\psr\J2EE>java ConstantsApp1noc--->3

SUDHEER REDDY

41

Page 42: J2EE Notes

POTHURAI

CONE CHARCTWO VARCHARCTHR NUMERIC

import java.sql.*;public class CLADBApp{

public static void main(String args[]) throws Exception{

String vdrvcls,vurl,vuname,vpwd;vdrvcls=System.getProperty("drvcls");vurl=System.getProperty("url");vuname=System.getProperty("uname");vpwd=System.getProperty("pwd");Class.forName(vdrvcls);Connection con=DriverManager.getConnection (vurl,vuname,vpwd);System.out.println("----Conneted to----->");DatabaseMetaData dbmd=con.getMetaData( );System.out.println(dbmd.getDatabaseProductName( ));System.out.println(dbmd.getDatabaseProductVersion( ));System.out.println(dbmd.supportsStoredProcedures( ));

}}

The above application will be able to establish the connection with any kind of database.D:\psr\J2EE>java -Ddrvcls=oracle.jdbc.driver.OracleDriver -Duname=system

–Dpwd=sunil -Durl=jdbc:oracle:thin:@localhost:1521:xe CLADBApp----Conneted to----->OracleOracle Database 10g Express Edition Release 10.2.0.1.0 - Productiontrue

If CLADBApp is executed using the above command, it will connect to Oracle server.

For connecting to MySqlD:\psr\J2EE>java -Ddrvcls=com.mysql.jdbc.Driver -Durl=jdbc:mysql://localhost:

3306/test CLADBApp----Conneted to-----> MySql

Note: - Even though SQL is a standard language different database servers supports slightly different grammar for SQL.

import java.sql.*;public class CLADDBApp{

SUDHEER REDDY

42

Page 43: J2EE Notes

POTHURAI

public static void main(String args[]) throws Exception{

String vdrvcls,vurl,vuname,vpwd;vdrvcls=System.getProperty("drvcls");vurl=System.getProperty("url");vuname=System.getProperty("uname");vpwd=System.getProperty("pwd");Class.forName(vdrvcls);Connection con=DriverManager.getConnection (vurl,vuname,vpwd);System.out.println("----Conneted to----->");DatabaseMetaData dbmd=con.getMetaData( );String dbname=dbmd.getDatabaseProductName( );String vsql=null;if(dbname.equals("MySql")){

vsql="create table ourtab (COne integer, CTwo float, CThr bit, CFour varchar(10))";

}if(dbname.equals("Oracle")){

vsql="create table ourtab (COne integer, CTwo float, CThr number(1), CFour varchar(10))";

}Statement stmt=con.createStatement( );stmt.executeUpdate(vsql);System.out.println(dbmd.getDatabaseProductName( ));System.out.println(dbmd.getDatabaseProductVersion( ));System.out.println(dbmd.supportsStoredProcedures( ));

}}

SQL> desc ourtab;ERROR:ORA-04043: object ourtab does not existD:\psr\J2EE>java -Ddrvcls=oracle.jdbc.driver.OracleDriver -Duname=system

–Dpwd=sunil -Durl=jdbc:oracle:thin:@localhost:1521:xe CLADDBApp----Conneted to----->OracleOracle Database 10g Express Edition Release 10.2.0.1.0 - ProductiontrueSQL> desc ourtab; Name Null? Type ----------------------------------------- -------- -------------- CONE NUMBER(38) CTWO FLOAT(126) CTHR NUMBER(1)

SUDHEER REDDY

43

Page 44: J2EE Notes

POTHURAI

CFOUR VARCHAR2(10)

D:\psr\J2EE>java -Ddrvcls=com.mysql.jdbc.Driver -Durl=jdbc:mysql://localhost: 3306/test CLADDBApp

1) We can use the products like JDO (java data object), TOPLINK, Hibernate etc…. to access the databases.

2) These products internally use JDBC API.3) As a developer we need not worry about the differences between the

databases when use the above products.

There are 4 types of JDBC drivers (Type-I, Type-II, Type-III & Type-IV)DB Native API: - To deal with oracle server from a ‘C’ program we can use a set of functions (API) provided by Oracle corporation as part of Oracle Client Software.

OCI API

MySql C API

A ‘C’ program can use oracle call interface (OCI), API deal with oracle. OCI is called as native API of Oracle.A ‘C’ program can use MySql C API, to deal with MySql server. MySql C API is called as native API of MySql server.

Like OCI, MySql C API a native API is provided for most of the databases.

JNI (java native interface): - public class ClsOne{

public void mone( ){

System.out.println("----Calling mtwo----");mtwo( );// (some) code in javaSystem.out.println("----called mtwo----");

SUDHEER REDDY

44

olog -- connect the oracle serverologof--disconnect the serveroparse--send the dataoexec -- executing the dataofetch -- get the data… etc

mysql_connectmysql_closemysql_row_fetchmysql_query…. etc

Page 45: J2EE Notes

POTHURAI

}public native void mtwo( );static{

try{

System.loadLibrary("ourfuncs");}catch (Exception e){}

}}

D:\psr\J2EE>javac ClsOne.javaD:\psr\J2EE>javah ClsOneD:\psr\J2EE>type ClsOne.h/* DO NOT EDIT THIS FILE - it is machine generated */#include <jni.h>/* Header for class ClsOne */#ifndef _Included_ClsOne#define _Included_ClsOne#ifdef __cplusplusextern "C" {#endif/* * Class: ClsOne * Method: mtwo * Signature: ( )V */JNIEXPORT void JNICALL Java_ClsOne_mtwo (JNIEnv *, jobject);#ifdef __cplusplus}#endif#endif

math.c

math.h

Prototype of functionImplementation of function

SUDHEER REDDY

45

int add(int i,int j){

int res=i+j;return res;

}int sub(int i,int j){

int res=i-j;return res;

}

int add(int,int)int sub(int,int)

Page 46: J2EE Notes

POTHURAI

We can use JNI technology for implementing the java code that can use the code implemented in C/C++ languages.

mtwo is declared as native. We must provide the code for this method in ‘C’ language.

ourfuncs.c

ourfuncs.dll/ourfuncs.so

Windows Unix/Linuxdll=dynamic link library, so=stored object.

Type II Driver: - The implementers of Type II Drivers provide the classes by mixing ‘C’ code with java code (for this JNI technology will be use). From the ‘C’ code the native API’S of the databases will be used (OCI in case of Oracle Driver, MySql C API in case of MySql).

SUDHEER REDDY

46

ClsOne.java

javac

ClsOne.Class

javah

Properties of the functions ClsOne.h

C/C++ code for the functions (Java_ClsOne_mtwo)

C compiler & (+) limker

m/l (machine language instructions) for the functions provided in C/C++ )

Page 47: J2EE Notes

POTHURAI

Type II Driver is not a pure java driver.If an application uses Type II Drivers, the following Steps must be

performed.

dll files

Native API of DB

1) Set the CLASSPATH pointing to the jar file that contains the classes of the JDBC driver.

D:\psr\J2EE>set CLASSPATH=ojdbc14.jar;.2) Install the client software (when we install Oracle client software, the dll files that contains OCI API & the dll’s that contains the ‘C’ code used from the java classes will be copied).3) Configure the client software (this is generally carried out by the database administrator).

We can use code as shown below for using the Type II Driver provided by Oracle Corporation. class.forName("oracle.jdbc.driver.OracleDriver");Connection con=DriverManager.getConnection ("jdbc:oracle:oci:@orans","scott", "tiger");

For using Type II Driver net service nameProvided by Oracle Corp.

Type II Driver provided by Oracle Corporation is called as OCI Driver by Oracle. Oracle Corp as they internally use OCI functions.

Ex: - import java.sql.*;public class Type2{

public static void main(String args[]) throws Exception{

Class.forName("oracle.jdbc.driver.OracleDriver ");Connection con=DriverManager.getConnection ("jdbc:oracle:oci:@orans","system","sunil");System.out.println("----Connected----");

}}

SUDHEER REDDY

47

Java classes

Code for imple in C lang

OCI in case of Oracle/ MySql C API in case of MySql.

Page 48: J2EE Notes

POTHURAI

D:\psr\J2EE>set CLASSPATH=ojdbc14.jar;.D:\psr\J2EE>javac Type2.javaD:\psr\J2EE>java Type2---Connected---Type IV Driver: - In case of Type IV Driver, the whole code is provided in java language. It is a pure java driver.

To run the application that uses Type IV Driver, the CLASSPATH must be set to point to the jar file that contains the class files of the driver.

We can use code as shown below for using the Type IV Driver provided by Oracle Corporation.

class.forName("oracle.jdbc.driver.OracleDriver");Connection con=DriverManager.getConnection ("jdbc:oracle:thin:@localhost: 1521:xe","scott","tiger");

Ex: - import java.sql.*;public class Type4{

public static void main(String args[]) throws Exception{

Class.forName("oracle.jdbc.driver.OracleDriver");Connection con=DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:xe","system","sunil");System.out.println("---Connected---");

}}

D:\psr\J2EE>javac Type4.javaD:\psr\J2EE>java Type4---Connected---

Type II Type IVJar file jar fileClient S/W

So Type IV Driver is thinner than Type II Driver.Oracle Corporation refers to its Type IV Drivers as thin driver.

Note: - As configuring the software that uses Type IV Driver & the modern JVM’S uses various optimization technologies to improve the speed of running the byte code. Most of the developers are preparing Type IV Drivers.

ODBC: - Open database connectivity (OJDBC) API: -

SUDHEER REDDY

48

Page 49: J2EE Notes

POTHURAI

ODBC API is an open specification. As part of ODBC specification, Micro Soft has provided the information regarding several functions in ‘C’ language. Any one can provide the implementation of ODBC Drivers.

ora.dll mysql.dll(ODBC Driver for Oracle) (ODBC Driver for MySql)

Type I Driver: - (JDBC – ODBC bridge). This driver is not a pure java driver. The implementer of these drivers uses the ‘C’ code from java code & the ‘C’ code internally uses the functions that are part of ODBC API.

Internally java soft has implemented Type I Driver as implementing. It is easy & the ODBC drivers are available for almost every database.

In order to use Type I Drivers we must follow the steps given below.1) Set the CLASSPATH referring to a jar file that contains the classes of JDBC

driver (if you are using Type I Driver of java soft then this is not required)

SUDHEER REDDY

49

….. sql Connect(…) {olog(….);….}….. sql disconnect(…) {olofoff(….);….}

….. sql Connect(…) {Mysql_connect(….);….}….. sql disconnect(…) {Mysql_close(….);…..}

Compiler + linker Compiler + linker

Java classes

‘C’ code

ODBC API

Native API (OCI etc)

Page 50: J2EE Notes

POTHURAI

2) Install the client software.3) Configure the client software.4) Install the ODBC driver.5) Configure the ODBC driver.

Code for using Type I Driver, provided by java soft. class.forName("sun.jdbc.odbc.JdbcOdbcDriver");Connection con = DriverManager.getConnection("jdbc:odbc:orads","scott", "tiger");

Data source name given while Configuring ODBC Driver

Ex: - import java.sql.*;public class Type1{

public static void main(String args[]) throws Exception{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver ");Connection con=DriverManager.getConnection ("jdbc:odbc:orads","system","sunil");System.out.println("---Connected---");

}}

D:\psr\J2EE>javac Type1.javaD:\psr\J2EE>java Type1---Connected---

Type III Driver: - It is pure java drivers.

DB srv

Net srv DB srv

Type III deals with a database through an application called as net server & these drivers are used for accessing the databases behind fire walls.

SUDHEER REDDY

50

Java App

Type I/II/IV drv

Type III drv

Java App

Page 51: J2EE Notes

POTHURAI

Serialization: - In java we can have interfaces without methods. These interfaces are called as tagged interfaces or marker interfaces. A tagged interface is mint for providing some sort of information about an object. java.io.Serializable, java.rmi.Remote …. Etc are examples of tagged interfaces.

public class CarA{

......... // CarA objects are not Serializable}public class CarB implements java.io.Serializable{

......... // CarB objects are Serializable.}

An object that implements Serializable interface is called as Serializable object. For every object there will be a state. Instance variables are part of an object & they hold the state of the object (static variables are not part of the object & they are not mend for holding the state of the object.)

Serialization is the process of writing the state of an object to a stream.

import java.io.Serializable;public class TLight implements Serializable{

private boolean isOn=false;public void switchOn( ){

isOn=true;}public void switchoff( ){

isOn=false;}public void displayState( ){

if(isOn==true){

System.out.println("---TLight is on---");}else{

System.out.println("---Tlight is off---");}

}}

D:\psr\J2EE>javac TLight.java

SUDHEER REDDY

51

Page 52: J2EE Notes

POTHURAI

public class ATLight{

private boolean isOn=false;public void switchOn( ){

isOn=true;}public void switchoff( ){

isOn=false;}public void displayState( ){

if(isOn==true){

System.out.println("---TLight is on---");}else{

System.out.println("---Tlight is off---");}

}}

D:\psr\J2EE>javac ATLight.java

The object of type TLight are Serializable & the object of type ATLight are non-Serializable

test.ser

Any extension import java.io.*;public class SerApp{

public static void main(String[] args) throws Exception{

FileOutputStream fos=new FileOutputStream("test.ser");ObjectOutputStream oos=new ObjectOutputStream(fos);TLight t1=new TLight( );

SUDHEER REDDY

52

oos

fos

t1

State of TLight obj

isOn=true

Page 53: J2EE Notes

POTHURAI

t1.switchOn( );t1.displayState( );oos.writeObject(t1);oos.close( );

}}D:\psr\J2EE>javac SerApp.javaD:\psr\J2EE>java SerApp---TLight is on---D:\psr\J2EE>type test.ser¼φ ♣sr ♠TLight‼i.╕ε↔¼"☻ ☺Z ♦isOnxp☺

When oos.writeObject( ) is called the state of the object will be return to the underling stream (in the above example FileOutputStream is the underling stream)

import java.io.*;public class SerApp1{

public static void main(String[] args) throws Exception{

FileOutputStream fos=new FileOutputStream("test1.ser");ObjectOutputStream oos=new ObjectOutputStream(fos);ATLight t1=new ATLight( );t1.switchOn( );t1.displayState( );oos.writeObject(t1);oos.close ( );

}}

D:\psr\J2EE>javac SerApp1.javaD:\psr\J2EE>java SerApp1---TLight is on---Exception in thread "main" java.io.NotSerializableException: ATLight at java.io.ObjectOutputStream.writeObject0(Unknown Source) at java.io.ObjectOutputStream.writeObject(Unknown Source) at SerApp1.main(SerApp1.java:11)D:\psr\J2EE>type test1.ser¼φ ♣{sr java.io.NotSerializableException(Vx τå▬5☻ xr↔java.io.ObjectStream Exceptiond├Σkì9√▀☻ xr ‼java.io.IOExceptionlÇsde%≡½☻ xr‼java.lang. Exception╨²▼>

If the object that is passed as a parameter is not serializable then an exception will be thrown by writeObject( ) method.

DeSerialization: - It is the process of reading the information about (state) of the object from a stream & creating on object using the information.

SUDHEER REDDY

53

Page 54: J2EE Notes

POTHURAI

import java.io.*;public class DSerApp{

public static void main(String[] args) throws Exception{

FileInputStream fis=new FileInputStream("test.ser");ObjectInputStream ois=new ObjectInputStream(fis);TLight tl=null;Object o=ois.readObject( );tl=(TLight)o;tl.displayState( );

}}

D:\psr\J2EE>javac DSerApp.javaD:\psr\J2EE>java DSerApp---TLight is on---

java.net.Socket, java.lang.Thread, java.sql.Connection etc… objects are not serializable.Ex: - import java.io.Serializable;public class TLight1 implements Serializable{

private boolean isOn;java.net.Socket sock;public void setState( ){

sock=new java.net.Socket();isOn=true;

}public void displayState( ){

System.out.println("isOn-->"+isOn);System.out.println("sock-->"+sock);

}}

D:\psr\J2EE>javac TLight1.java

import java.io.*;public class SerApp2{

public static void main(String[] args) throws Exception{

FileOutputStream fos=new FileOutputStream("test2.ser");

SUDHEER REDDY

54

Page 55: J2EE Notes

POTHURAI

ObjectOutputStream oos=new ObjectOutputStream(fos);TLight1 t1=new TLight1( );t1.setState( );t1.displayState( );oos.writeObject(t1);oos.close( );

}}

D:\psr\J2EE>javac SerApp2.javaD:\psr\J2EE>java SerApp2isOn-->truesock-->Socket[unconnected]Exception in thread "main" java.io.NotSerializableException: java.net.Socket at SerApp2.main(SerApp2.java:11)

import java.io.*;public class DSerApp2{

public static void main(String[] args) throws Exception{

FileInputStream fis=new FileInputStream("test2.ser");ObjectInputStream ois=new ObjectInputStream(fis);TLight1 tl=null;Object o=ois.readObject( );tl=(TLight1)o;tl.displayState( );

}}

D:\psr\J2EE>javac DSerApp2.javaD:\psr\J2EE>java DSerApp2Exception in thread "main" java.io.WriteAbortedException: writing aborted; java.io.NotSerializableException: java.net.Socket at DSerApp2.main(DSerApp2.java:9)Caused by: java.io.NotSerializableException: java.net.Socket at SerApp2.main(SerApp2.java:11)

SUDHEER REDDY

55

sockTLight1

isOn= true sock

Page 56: J2EE Notes

POTHURAI

Serialization of TLight1 object fails as the sock variable points to a Socket object. Which is not Serializable?

We can solve the above problem by declaring the instance variable sock as transient.

import java.io.Serializable;public class TLight1 implements Serializable{

private boolean isOn;transient java.net.Socket sock;static int notl=0;public void setState( ){

sock=new java.net.Socket( );isOn=true;notl=10;

}public void displayState( ){

System.out.println("isOn-->"+isOn);System.out.println("sock-->"+sock);System.out.println("notl-->"+notl);

}}

D:\psr\J2EE>javac TLight1.javaD:\psr\J2EE>java SerApp2isOn-->truesock-->Socket[unconnected]notl-->10D:\psr\J2EE>java DSerApp2isOn-->truesock-->nullnotl-->0

During serialization the information about non static, non transient variables will be serialized.

When we need to declare an instance variable as transient?A) If an instance variable (sock) of an object (Tlight1) points to a non-Serializable object (java.netSocket) then we must declare the variable as transient.

How to take care of special requirements like writing the information about the static variables during serialization?A) In order to take care of special requirements we must implements the methods writeObject( ) & readObject( ) in our class.

SUDHEER REDDY

56

Page 57: J2EE Notes

POTHURAI

Ex: - import java.io.*;public class TLight2 implements Serializable{

private boolean isOn=true;static int notl=0;private void writeObject(ObjectOutputStream out) throws IOException{

System.out.println("---our write object---");out.writeBoolean(isOn);out.writeInt(notl);

}private void readObject(ObjectInputStream in) throws IOException,

ClassNotFoundException{

System.out.println("---our read object---");isOn=in.readBoolean( );notl=in.readInt( );

}}D:\psr\J2EE>javac TLight2.java

import java.io.*;public class SerApp{

public static void main(String[] args) throws Exception{

FileOutputStream fos=new FileOutputStream("test2.ser");ObjectOutputStream oos=new ObjectOutputStream(fos);TLight2 t1=new TLight2( );oos.writeObject(t1);oos.close( );

}}

When oos.writeObject( ) is called it internally uses the code implemented in C (consider to be part of JVM). This code calls writeObject( ) method provided by us in our class.

D:\psr\J2EE>javac SerApp.javaD:\psr\J2EE>java SerApp---our write object---

import java.io.*;public class DSerApp{

public static void main(String[] args) throws Exception{

FileInputStream fis=new FileInputStream("test2.ser");

SUDHEER REDDY

57

Page 58: J2EE Notes

POTHURAI

ObjectInputStream ois=new ObjectInputStream(fis);ois.readObject( );

}}

When ois.readObject( ) is called, it internally uses code implemented in C (consider to be part of JVM). This code calls read object method provided by us in our calls.D:\psr\J2EE>javac DSerApp.javaD:\psr\J2EE>java DSerApp---our read object---

Java soft has defined as a format called java Serialization protocol. When Serializable interface is implemented the information about will be stored using this format. If we want to store the information about the object in our format then we must implement java.io.Externalizable interface.

To simplify the development of application instead of using JDBC API directly we can use JDO (java data object), TopLink, Hibernate etc… These products are called as ORM (object relational mapping) products.

The Entity Beans (EJB) that are part of EJB 1.x & 2.x can be used only as part of EJB applications. As these entity beans kills the performance of the applications. Most of the developers are not using these beans. As part of EJB 3.x java soft has re-designed the entity beans & this designed is similar to Hibernate, Top Link etc…. The entity beans of EJB 3.0 can be used as part of any kind of java applications.

To access the data available in a table using Hibernate, we need to provide POJO (plain old java object), hbm (hibernate mapping) file.

employee

To access the data available in the above table using hibernate, we must provide a POJO class as shown belowpackage org.students;public class Employee{

private Long empno;private String ename;private Double salary;public void setEmpNo(Long empNo){

this.empNo=empNo;}public Long getEmpNo( )

SUDHEER REDDY

58

empno ename salary

1 EOne 100002 ETwo 200003 EThr 30000

Page 59: J2EE Notes

POTHURAI

{return this.empNo;

}public void setEname(String ename){

this.empNo=ename;}public String getEname( ){

return this.ename;}public void setSalary(Double salary){

this.empNo=salary;}public Double getSalary( ){

return this.salary;}

}The above class can consider as java bean also. According to java bean

standard a property with name xxx can be supported by a java bean using public void setXxx(Type p)public p getXxx( )

org.students.Employee class supports the following properties.

one.hbm.xml

hbm files contains the information regarding the mapping between the POJO classes & the tables that has to be access by hibernate.

We can use the tools like myeclipseide, exader studio, weblogic workshop etc…for generating 1) POJO classes 2) hbm files 3) hibernate configuration file (cfg)

SUDHEER REDDY

59

Property type property name

java.lang.Long empNo java.lang.String ename java.lang.Double salary

org.students.Employee employee

empNoempnoeneme enamesalary salary

Page 60: J2EE Notes

POTHURAI

SQL> create table employee (eno number primary key, ename varchar(15),age number, salary number(10,2));Table created.SQL> desc employee; Name Null? Type ----------------------------------------- -------- ------------------- ENO NOT NULL NUMBER ENAME VARCHAR2(15) AGE NUMBER SALARY NUMBER(10,2)SQL> create table product (pid number primary key, prodname varchar(15),price number(10,2));Table created.SQL> desc product; Name Null? Type ----------------------------------------- -------- ---------------------------- PID NOT NULL NUMBER PRODNAME VARCHAR2(15) PRICE NUMBER(10,2)Procedure for setting up myeclipseide: -

1) Create a work space directory (ex: - D:\psr\J2EE\eclws)2) Copy the jdbc driver (ex: - ojdbc14.jar) to the directory created in step 13) Start myeclipseide(start programs My Eclipse)4) In the work space launcher click on the browse button & choose the

directory created in step1.

5) Click on the ok button in work space launcher.6) Choose My Eclipse database explorer prospective.

SUDHEER REDDY

60

Page 61: J2EE Notes

POTHURAI

7) Right click in DB browser view to get the popup menu & choose new option.

8) Click on “configure database driver” available in profile window.

9) Click on the new button in performance window.10) Click on add jar’s button in new driver window & choose the jar file that

was copied in step2.11) Choose oracle thin driver as Driver template & click on OK button in new

driver window.

SUDHEER REDDY

61

Page 62: J2EE Notes

POTHURAI

12) Click on OK button in preferences window

13) Provide the information shown below & click on finish button in database profile window.

SUDHEER REDDY

62

Page 63: J2EE Notes

POTHURAI

Note: - The information providing in the above step will be stored in the files related to myeclipseide. At this information will be use by eclipse to connect to oracle server.

Procedure for creating a project that uses hibernate: - 1) Choose java prospective.

2) Chose file new project

3) In new project window choose java project & click on next button.

SUDHEER REDDY

63

Page 64: J2EE Notes

POTHURAI

4) In the new project window provide the project name (ex: - hibproj, choose create separate source & output folders option & click on finish button)

Note: - myeclipseide creates various folders under the workspace directory as shown below

D:\ psr

J2EE

SUDHEER REDDY

64

Page 65: J2EE Notes

POTHURAI

HibProj1 used for .class files.binsrc used for .java files

5) In package explorer choose the project, choose myeclipse & add hibernate capabilities.

6) In new hibernate project window check all the check boxes & click on the next button.

7) Click on next button.

8) Select oraprof as DB profile & click on next.

SUDHEER REDDY

65

Page 66: J2EE Notes

POTHURAI

9) Provide SessionFactory class (ex: - org.students.OraSF) & click on finish.

Note: - myeclipse creates 1) hibernate.cfg.xml 2) oraSF.java (class name: org.students.OraSFNote: - As part of hibernate.cfg.xml the information that is required to establish the database connections (driver class, url, uname, pwd) & the information about hbm files will be provide.Procedure for generating POJO classes & hbm files: -

1) Choose myeclipse database explorer in prospective.

SUDHEER REDDY

66

Page 67: J2EE Notes

POTHURAI

2) Right click on oraprof & click on open connection.

3) Click on ok button in open database connection window.

4) Choose the tables & right click to get a popup menu & click on create hibernate mapping.

SUDHEER REDDY

67

Page 68: J2EE Notes

POTHURAI

5) In hibernate reverse engineering windowa) Click on browse button & choose src folderb) Provide java package (org.students)c) Uncheck create abstract class.d) Click on finish.

Note: - myeclipse creates the POJO classes, hbm files and adds the information about the hbm files to hibernate.cfg.xml.

1) In order to use hibernate org.hibernate.Session object is required.2) To create a Session object org.hibernate.SessionFactory object is required.3) To create a SessionFactory object org.hibernate.cfg.configuration object is

required.

SUDHEER REDDY

68

Page 69: J2EE Notes

POTHURAI

configure( )

hibernate.cfg.xml org.hibernate.cfg.configuration

buildSessionFactory( )

org.hibernate.SessionFactory

openSession( )… hbm files

org.hibernate.sessionhibernate.cfg.xml: - (code)<?xml version='1.0' encoding='UTF-8'?><!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"><!-- Generated by MyEclipse Hibernate Tools. --><hibernate-configuration>

<session-factory><property name="connection.username">system</property><property name="connection.url">jdbc:oracle:thin:@localhost:1521

:xe</property><property name="dialect">org.hibernate.dialect.Oracle9Dialect </property><property name="myeclipse.connection.profile">orans</property><property name="connection.password">sunil</property><property name="connection.driver_class">oracle.jdbc.driver.

OracleDriver</property><mapping resource="org/sunil/Employee.hbm.xml" /><mapping resource="org/sunil/Product.hbm.xml"></mapping>

</session-factory></hibernate-configuration>

Employee.hbm.xml: - (code)<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN""http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><!--

SUDHEER REDDY

69

drvcls,uname,pwd,url … etc+

info of hbm files

Mapping b/w classes & tables

Page 70: J2EE Notes

POTHURAI

Mapping file autogenerated by MyEclipse - Hibernate Tools--><hibernate-mapping> <class name="org.sunil.Employee" table="EMPLOYEE" schema="SYSTEM"> <id name="eno" type="long"> <column name="ENO" precision="22" scale="0" /> primary key <generator class="assigned" /> </id> <property name="ename" type="string"> <column name="ENAME" length="15" /> </property> <property name="age" type="long"> <column name="AGE" precision="22" scale="0" /> </property> <property name="salary" type="double"> <column name="SALARY" precision="10" /> </property> </class></hibernate-mapping>

configure( ) method reads the information available in cfg file & hbm files. As there will be lot of information available in these files, configure( ) method takes more amount of time to read the information (that is configure( ) method is expensive). This method should be called only once by the application.

When buildSessionFactory( ) method is called hibernate decides about various sql statements that has to be used to access various tables (this takes more amount of time) & creates SessionFactory object. This operation is expensive & it should be used only once.

openSession( ) method creates a Session objects & it is not expensive.

package org.sunil;import org.hibernate.*;import org.hibernate.cfg.*;public class HibApp1 {

public static void main(String[] args)throws Exception {

Configuration conf=new Configuration( );conf.configure( );SessionFactory sf=conf.buildSessionFactory( );Session hsession=sf.openSession();// code to perform DB oparationshsession.close( );

}}

A business application performs the following 4 operations.1) create –- store the data (insert)

SUDHEER REDDY

70

Page 71: J2EE Notes

POTHURAI

2) update –- modify the data (update)3) read -– get the data (select)4) delete –- remove the data (delete)

The code shown below performs the create operation.

package org.sunil;import org.hibernate.*;import org.hibernate.cfg.*;public class HibApp1 {

public static void main(String[] args)throws Exception {Configuration conf=new Configuration( );conf.configure( );SessionFactory sf=conf.buildSessionFactory( );Session hsession=sf.openSession( );// code to perform DB oparationsTransaction tx=hsession.beginTransaction( );Employee emp1=new Employee( );emp1.setEno(1);emp1.setEname("EOne");emp1.setAge(21);emp1.setSalary(10000);Employee emp2=new Employee( );emp2.setEno(2);emp2.setEname("ETwo");emp2.setAge(22);emp2.setSalary(20000);Employee emp3=new Employee( );emp3.setEno(3);emp3.setEname("EThr");emp3.setAge(23);emp3.setSalary(30000);hsession.save(emp1);hsession.save(emp2);hsession.save(emp3);tx.commit( );hsession.close( );}

}

SQL> select * from employee;no rows selectedSQL> commit;Commit complete.

SUDHEER REDDY

71

Page 72: J2EE Notes

POTHURAI

SQL> select * from employee; ENO ENAME AGE SALARY ---------- --------------- ---------- ---------- 1 EOne 21 10000 2 ETwo 22 20000 3 EThr 23 30000

An application must used save method to ask hibernate to store/insert the data in the database.

package org.sunil;import org.hibernate.*;import org.hibernate.cfg.*;public class HibApp2 {

public static void main(String[] args)throws Exception {Configuration conf=new Configuration( );conf.configure( );SessionFactory sf=conf.buildSessionFactory( );Session hsession=sf.openSession( );// code to perform DB oparationsEmployee emp=new Employee( );hsession.load(emp,new Long(1));System.out.println(emp.getEno( ));System.out.println(emp.getEname( ));System.out.println(emp.getAge( ));System.out.println(emp.getSalary( ));hsession.close( );}

}

HibApp2 Run As Java Application1EOne

SUDHEER REDDY

72

Page 73: J2EE Notes

POTHURAI

2110000.0

The process of getting the data from the database & storing the data inside the java object created based on a POJO class that is mapped to the table is called as loading.

java.util.Hashtable can be used any number of & any type of java products. For storing any thing in hash table many to use a key & a value. The combination of the key & the value is called as hash table entry.

Hashtable cache=new Hashtable( );cache.put(“KOne”,“VOne”);cache.put(“KTwo”,“VTwo”);cache.put(“KThr”,“VThr”);

cache

Ht Entry

java.util.Hashtable

Hibernate internally uses the objects based on the classes similar to Hashtable for holding / caching the java object.

SessionFactory sf=sf.buildSessionFactory( );When SessionFactory is created Hashtable kind of class will be used

to create an object. This object will be associated with SessionFactory & this object is called as first level cache.

sf First level cache

Session hsession=sf.openSession( );

SUDHEER REDDY

73

KOne

VOne

KTwo

VTwo

VThr

KThr

cache

Hashtable kind of object

Page 74: J2EE Notes

POTHURAI

When a Session object is created internally an object similar to Hashtable will be created & it will be associated with Session object. This is called second level cache.

hsession Second level cache

To see the SQL statements that are executed by Hibernate, we must add the following line to hibernate.cfg.xml

<property name= “show_sql”>true </property>

When hsession.save(emp); is executed hibernate stores the reference of employee object in the second level cache as shown in the diagram.

emp

hsession Second level cache

To be stored Employee

When tx.commit( ); is executed Hibernate performs the following steps.1) Checks for the objects in the second level cache.2) Identifies the operations that have to be performed on the database.3) Execute the SQL statements (in the above application insert statement will be

executed).4) Commits the transaction.

Note: - Hibernate uses batch update feature or JDBC to improve the performance.

hsession.load(emp,new Long(1));When the load method is executed hibernate performs the following steps: -

1) Hibernate executes the select statement.2) Hibernate gets the data from the database & calls the setters on the POJO

object to put the data in the object.3) Hibernate stores the reference of the POJO object & the second level cache.

SQL> select * from employee; ENO ENAME AGE SALARY ---------- --------------- ---------- ---------- 1 EOne 21 10000 2 ETwo 22 20000 3 EThr 23 30000

SUDHEER REDDY

74

cache

Hashtable kind of object

cache

Hashtable kind of object

1EOne

2110000

Page 75: J2EE Notes

POTHURAI

package org.sunil;import org.hibernate.*;import org.hibernate.cfg.*;public class HibApp3 {

public static void main(String[] args)throws Exception {Configuration conf=new Configuration( );conf.configure( );SessionFactory sf=conf.buildSessionFactory( );Session hsession=sf.openSession( );// code to perform DB oparationsTransaction tx=hsession.beginTransaction( );Employee emp1=new Employee( );Employee emp2=new Employee( );hsession.load(emp1,new Long(1));hsession.load(emp2,new Long(2));emp1.setSalary(25000);emp1.setAge(25);emp2.setSalary(26000);emp2.setAge(26);System.out.println("----Calling commit----");tx.commit( );hsession.close( );}

}

1--->The data will be obtained [1,EOne,21,10000] & it will be loaded in employee object referred by emp1 & this object will be placed in the cache.2--->The data will be obtained [2,ETwo,22,20000] & it will be loaded in employee object referred by emp2 & this object will be placed in the cache.

emp1

Employee

emp2 hsession SL cache

EmployeeWhen the setters are executed the data available in the object will be modified (that is the objects become dirty).3---> When commit is called hibernate identify that there are 2 dirty objects in the cache & it’s execute update statements to modify the data in employee table.

SUDHEER REDDY

75

1EOne

2110000

2ETwo

2220000

Page 76: J2EE Notes

POTHURAI

HibApp3 Run As Java ApplicationHibernate: select employee0_.ENO as ENO0_, employee0_.ENAME as ENAME0_0_, employee0_.AGE as AGE0_0_, employee0_.SALARY as SALARY0_0_ from SYSTEM.EMPLOYEE employee0_ where employee0_.ENO=?Hibernate: select employee0_.ENO as ENO0_, employee0_.ENAME as ENAME0_0_, employee0_.AGE as AGE0_0_, employee0_.SALARY as SALARY0_0_ from SYSTEM.EMPLOYEE employee0_ where employee0_.ENO=?----Calling commit----Hibernate: update SYSTEM.EMPLOYEE set ENAME=?, AGE=?, SALARY=? where ENO=?Hibernate: update SYSTEM.EMPLOYEE set ENAME=?, AGE=?, SALARY=? where ENO=?

SQL> select * from employee; ENO ENAME AGE SALARY ---------- --------------- ---------- ---------- 1 EOne 25 25000 2 ETwo 26 26000 3 EThr 23 30000

evict( ) method is used to detach the object from the session catch. package org.sunil;import org.hibernate.*;import org.hibernate.cfg.*;public class HibApp4 {

public static void main(String[] args)throws Exception {Configuration conf=new Configuration( );conf.configure( );SessionFactory sf=conf.buildSessionFactory( );Session hsession=sf.openSession( );// code to perform DB oparationsTransaction tx=hsession.beginTransaction( );Employee emp1=new Employee( );hsession.load(emp1,new Long(3)); --->1emp1.setSalary(35000);emp1.setAge(27);hsession.evict(emp1); --->2//hsession.update(emp1);tx.commit( ); --->3hsession.close( );}

}

1---> Employee object will be attaching to the Session cache.2---> The Employee object will be detached from the Session cache.

SUDHEER REDDY

76

Page 77: J2EE Notes

POTHURAI

3---> update statement will be not being executed as the Employee object is not available in the Session cache.

HibApp4 Run As Java ApplicationHibernate: select employee0_.ENO as ENO0_, employee0_.ENAME as ENAME0_0_, employee0_.AGE as AGE0_0_, employee0_.SALARY as SALARY0_0_ from SYSTEM.EMPLOYEE employee0_ where employee0_.ENO=?

SQL> select * from employee; ENO ENAME AGE SALARY ---------- --------------- ---------- ---------- 1 EOne 25 25000 2 ETwo 26 26000 3 EThr 23 30000

update( ) method attaches the object to the Session cache. An application can use delete( ) method to ask hibernate to delete the data from database.

package org.sunil;import org.hibernate.*;import org.hibernate.cfg.*;public class HibApp5 {

public static void main(String[] args)throws Exception {Configuration conf=new Configuration( );conf.configure( );SessionFactory sf=conf.buildSessionFactory( );Session hsession=sf.openSession( );// code to perform DB oparationsTransaction tx=hsession.beginTransaction( );Employee emp1=new Employee( );emp1.setEno(1);emp1.setEname("Sudheer");emp1.setSalary(18000);emp1.setAge(23);hsession.update(emp1);Employee emp2=new Employee( );hsession.load(emp2,new Long(3));hsession.delete(emp2);tx.commit( );hsession.close( );}

}

HibApp5 Run As Java ApplicationHibernate: select employee0_.ENO as ENO0_, employee0_.ENAME as ENAME0_0_, employee0_.AGE as AGE0_0_, employee0_.SALARY

SUDHEER REDDY

77

Load --- attachEvict --- detach

Update --- reattach & attach (not load

method in the application)

Page 78: J2EE Notes

POTHURAI

as SALARY0_0_ from SYSTEM.EMPLOYEE employee0_ where employee0_.ENO=?Hibernate: update SYSTEM.EMPLOYEE set ENAME=?, AGE=?, SALARY=? where ENO=?Hibernate: delete from SYSTEM.EMPLOYEE where ENO=?SQL> select * from employee; ENO ENAME AGE SALARY ---------- ------------------ ---------------- -------------- 1 Sudheer 23 18000 2 ETwo 26 26000

SQL> insert into employee (eno,ename) values (3,'EThr');1 row created.SQL> select * from employee; ENO ENAME AGE SALARY---------- --------------------------- ----------------- ----------- 3 EThr 1 Sudheer 23 18000 2 ETwo 26 26000

long vone=null; invalid, we can set long, int etc var’s (primitive data types) to nullLong vtwo=null; valid;

If the data type of a property in a POJO class is primitive data type & if the column, that is mapped to the property contains null. Then hibernate will fail as it can not set null in the primitive data type variable.

public class Employee {…….

double salary;public double getSalary( ) {

return this.salary; } public void setSalary(double salary) { this.salary = salary; }}

Salary property is of type double (primitive data type). If it is mapped to a column salary is null then hibernate will fail to set the value of the property.

To avoid this problem we can use the wrapper classes of primitive data types like java.lang.Long, java.lang.Double etc… as the data types of the properties in the POJO classes.

Note: - while generating the POJO classes using myeclipseide choose the option java types for generating the properties with wrapper classes of primitive data types as the data type of the properties.

SUDHEER REDDY

78

Page 79: J2EE Notes

POTHURAI

Form Two Form One

It will be easy for the end user to fill (work) form Two. In case of form two end user need not provide the value of Emp no on his own. In this case the application must generate the value of Emp no.

Hibernate supports various ways / strategies / algorithms for generating the value of the primary key fields.

As part of the hbm file, we must specify the generator tag in the id tag as shown below.

<id name="eno" type="java.lang.Long"> <column name="ENO" precision="22" scale="0" /> <generator class="assigned" /> </id>

SUDHEER REDDY

79

Emp noEmp name Age Salary

Emp name Age Salary

StoreStore

Page 80: J2EE Notes

POTHURAI

The value of the Eno must be set (assigned) by the application before calling save method. <id name="eno" type="java.lang.Long"> <column name="ENO" precision="22" scale="0" /> <generator class="increment" /> </id>The value of Eno need not be set (assigned) by the application before calling save method. Hibernate generates the value of Eno in this case.

Like increment hibernate supports hilo, guid (globally unique id), native (Oracle : Hibernate uses sequences for generating the value for the column) (MySql: Hibernate uses auto increment feature supported by MySql).

SQL> delete from employee;3 rows deleted.SQL> commit;Commit complete.SQL> select * from employee;no rows selected

package org.sunil;import org.hibernate.*;import org.hibernate.cfg.*;public class HibApp6 {

public static void main(String[] args)throws Exception {Configuration conf=new Configuration( );conf.configure( );SessionFactory sf=conf.buildSessionFactory( );Session hsession=sf.openSession( );// code to perform DB oparationsTransaction tx=hsession.beginTransaction( );Employee emp1=new Employee( );emp1.setEname("Sunil");emp1.setSalary(new Double(30000));emp1.setAge(new Long(24));Employee emp2=new Employee( );emp2.setEname("Sudheer");emp2.setSalary(new Double(20000));emp2.setAge(new Long(23));hsession.save(emp1); --- > 1hsession.save(emp2); --- > 2tx.commit( ); hsession.close( );}

}

Assumption: - <generator class = “increment”/> is used 1,2 : when save method is called hibernate generates the value of Eno automatically.

SUDHEER REDDY

80

Page 81: J2EE Notes

POTHURAI

HibApp6 Run As Java ApplicationSQL> select * from employee; ENO ENAME AGE SALARY ---------- ------------------- --------------------- --------------- 1 Sunil 24 30000 2 Sudheer 23 20000

**What is the issues that we need to take care of while dealing with legacy databases?

Employee

Primary keyEaddrs (design one)

Note: - Hibernate manuals recommends that we must avoid the tables with multiple columns in primary key.

Primary keyEaddrs (design two)

Hibernate performs better when eaddr shown in design two is used.We may need to used tables with multiple columns in primary key while

developing the apps using legacy database. In this case we must provide a PRIMARY KEY Class.SQL> create table eddrs (eno number(4), addrno number(4), street varchar(10), city varchar(10), state varchar(10), primary key (eno,addrno));Table created.SQL> desc eddrs;

SUDHEER REDDY

81

Eno ename age salary1 EOne 21 100002 ETwo 22 20000

Eno addrno street city state1 1 xx yy zz 1 2 aa bb zz2 1 xxx yyy zzz2 2 aaa bbb zzz2 3 mmm nnn zzz

Eno addrno street city state1 1 xx yy zz 1 2 aa bb zz2 1 xxx yyy zzz2 2 aaa bbb zzz2 3 mmm nnn zzz

eaddrid12345

Page 82: J2EE Notes

POTHURAI

Name Null? Type ----------------------------------------- -------- ---------------------------- ENO NOT NULL NUMBER(4) ADDRNO NOT NULL NUMBER(4) STREET VARCHAR2(10) CITY VARCHAR2(10) STATE VARCHAR2(10)

To deal with eddrs table shown in design one, the following 2 classes must be used.

Eaddrsid

EaddrsNote: - We must use <composite-id> tag instead of <id>tag in the hbm file.Note: - We need to follow the recommendations given below while providing the primary key class.

1) The class must implement java.io.Serializable interface.2) The class must support the properties that must be mapped to the columns of

the primary keys.3) Provide equals & hash code methods.

Note: - equals( ) method should return true, both the objects represents the same primary key otherwise it must return false.Note: - hashcode( ) method should return the same value for two different objects that represents the same primary key.

package org.sunil;import org.hibernate.*;import org.hibernate.cfg.*;public class HibApp7 {

public static void main(String[] args)throws Exception {Configuration conf=new Configuration( );conf.configure( );SessionFactory sf=conf.buildSessionFactory( );Session hsession=sf.openSession( );// code to perform DB oparationsTransaction tx=hsession.beginTransaction( );EddrsId pk1=new EddrsId( );pk1.setEno(new Long(1));pk1.setAddrno(new Long(1));EddrsId pk2=new EddrsId( );pk2.setEno(new Long(1));pk2.setAddrno(new Long(2));EddrsId pk3=new EddrsId( );

SUDHEER REDDY

82

id Eaddrsidstreet Stringcity Stringstate String

eno Longaddrno Long

PRIMARY KEY Class

Page 83: J2EE Notes

POTHURAI

pk3.setEno(new Long(1));pk3.setAddrno(new Long(2));System.out.println("pk1--->"+pk1.hashCode( ));System.out.println("pk2--->"+pk2.hashCode( ));System.out.println("pk3--->"+pk3.hashCode( ));System.out.println(pk1.equals(pk2));;System.out.println(pk2.equals(pk3));tx.commit( );hsession.close( );

}}HibApp7 Run As Java Applicationpk1--->23311pk2--->23312pk3--->23312falsetrue

Hibernate supports hibernate query language. Our code must provide a statement in HQL to hibernate. Hibernate converts HQL to SQL. While converting hibernate takes care of the differences in the SQL that is supported by various data types.

The names of the properties of a POJO class need not be same as the column names in the table.

Property names Column names

SUDHEER REDDY

83

Oracle

MySql

Our code gives HQL

Hibernate translate HQL to SQL

org.sunil.Employee employee

empNoempNameempAge

empSalary

enoename

agesalary

Page 84: J2EE Notes

POTHURAI

Note: - As part of the HQL we must use the names of the POJO classes instead of the names of the tables.

As part of the SQL we can use the property names instead of the column names. Table nameSQL: - select * from employee;HQL: - from org.sunil.Employee

Name of the POJO class mapped to employee table.

List object Employee obj

… Employee obj … Employee obj … Employee obj

Employee obj

SQL> create table employee (eno number(3) primary key, ename varchar(15),age number(4), salary number(10,2));Table created.SQL> insert into employee values (1,'EOne',21,10000);1 row created.SQL> insert into employee values (2,'ETwo',22,20000);1 row created.SQL> insert into employee values (3,'EThr',23,30000);1 row created.SQL> insert into employee values (4,'EFour',24,40000);1 row created.SQL> insert into employee values (5,'EFive',25,50000);1 row created.SQL> select * from employee; ENO ENAME AGE SALARY ---------- --------------- --------------- -------------------- 1 EOne 21 10000 2 ETwo 22 20000 3 EThr 23 30000 4 EFour 24 40000 5 EFive 25 50000SQL> commit; Commit complete.

SUDHEER REDDY

84

1EOne

2110000

5EFive

2550000

Page 85: J2EE Notes

POTHURAI

package org.sunil;import org.hibernate.*;import org.hibernate.cfg.*;import java.util.*;public class HibApp8 {

public static void main(String[] args)throws Exception {Configuration conf=new Configuration( );conf.configure( );SessionFactory sf=conf.buildSessionFactory( );Session hsession=sf.openSession( );// code to perform DB oparationsTransaction tx=hsession.beginTransaction( );String vhql="from org.sunil.Employee";Query qry=hsession.createQuery(vhql);List empList=qry.list( );for(int i=0;i<empList.size();i++){

Object o=empList.get(i);Employee e=(Employee)o;System.out.print(e.getEno( ));System.out.print("\t"+e.getEname( ));System.out.print("\t"+e.getAge( ));System.out.println("\t"+e.getSalary( ));

}tx.commit( );hsession.close( );

}}

The code shown above gets the data from employee table & generates reports based on the information.

List empList=qry.list( ); When qry.list( ) is executed the following steps carried out by hibernate.

1) HQL will convert into SQL.2) SQL will be executed.3) Data will be obtained from the database table employee.4) Creates five employee objects, loads the data in employee object, and places

the employee objects inside a list object.5) The list of objects will be attached to the Session cache.

HibApp8 Run As Java Application1 EOne 21 10000.02 ETwo 22 20000.03 EThr 23 30000.04 EFour 24 40000.05 EFive 25 50000.0

SQL> insert into product values (1,'pen',100.00);1 row created.

SUDHEER REDDY

85

Page 86: J2EE Notes

POTHURAI

SQL> insert into product values (2,'pencil',50.00);1 row created.SQL> select * from product; PID PRODNAME PRICE---------- ------------------- ------------------- 1 pen 100 2 pencil 50SQL> commit;Commit complete.

We can use the code shown below to remove all the rows from product table. package org.sunil;import org.hibernate.*;import org.hibernate.cfg.*;import java.util.*;public class HibApp9 {

public static void main(String[] args)throws Exception {Configuration conf=new Configuration( );conf.configure( );SessionFactory sf=conf.buildSessionFactory( );Session hsession=sf.openSession( );// code to perform DB oparationsTransaction tx=hsession.beginTransaction( );String vhql="from org.sunil.Product";Query qry=hsession.createQuery(vhql);List prodList=qry.list( );for(int i=0;i<prodList.size( );i++){

Product p=(Product)prodList.get(i);hsession.delete(p);

}tx.commit( );hsession.close( );

}}

HibApp9 Run As Java ApplicationSQL> select * from product;no rows selected

class ArrayApp{

public static void main(String[] args) {

Object o[][]=new Object[10][10];Integer i[][]=new Integer[10][10];Byte by[]=new Byte[10];Boolean b[]=new Boolean[10];

SUDHEER REDDY

86

Page 87: J2EE Notes

POTHURAI

System.out.println(o);System.out.println(i);System.out.println(by);System.out.println(b);

}}

D:\psr\J2EE>javac ArrayApp.javaD:\psr\J2EE>java ArrayApp[[Ljava.lang.Object;@10b62c9[[Ljava.lang.Integer;@82ba41[Ljava.lang.Byte;@923e30[Ljava.lang.Boolean;@130c19b

Here [[=multi dimensional array, [=single dimensional array.

SQL> select e.ename, e.salary from employee e; // Here e means Elias.ENAME SALARY--------------- --------------------EOne 10000ETwo 20000EThr 30000EFour 40000EFive 50000

package org.sunil;import org.hibernate.*;import org.hibernate.cfg.*;import java.util.*;public class HibApp10 {

public static void main(String[] args)throws Exception {Configuration conf=new Configuration( );conf.configure( );SessionFactory sf=conf.buildSessionFactory( );Session hsession=sf.openSession( );// code to perform DB oparationsTransaction tx=hsession.beginTransaction( );

String vhql="select e.ename,e.salary,e.age from org.sunil.Employee as e";Query qry=hsession.createQuery(vhql);List empList=qry.list( );for(int i=0;i<empList.size( );i++){

Object o=empList.get(i);Object arr[]=(Object[])o;System.out.println(arr[0]);System.out.println(arr[1]);System.out.println(arr[2]);System.out.println("-------");System.out.println(arr.length);

SUDHEER REDDY

87

Page 88: J2EE Notes

POTHURAI

}tx.commit( );hsession.close( );

}}HibApp10 Run As Java ApplicationEOne10000.021-------3ETwo20000.022-------3EThr30000.023-------3EFour40000.024-------3EFive50000.025-------3

As 3 properties are chosen hibernate creates a single dimension object array for every row & the size of the array 3.

Object [] length=3

Object [] length=3 List

SUDHEER REDDY

88

EOne

10000

21

ESix

60000

26

Get employee details

Page 89: J2EE Notes

POTHURAI

SQL> insert into employee values (6,'ESix',26,60000);1 row created.

SQL> select * from employee; ENO ENAME AGE SALARY------------ --------------------- ---------------------- ---------- 1 EOne 21 10000 2 ETwo 22 20000 3 EThr 23 30000 4 EFour 24 40000 5 EFive 25 50000 6 ESix 26 60000

package org.sunil;import org.hibernate.*;import org.hibernate.cfg.*;import java.util.*;public class HibApp11 {

public static void main(String[] args)throws Exception {Configuration conf=new Configuration( );conf.configure( );SessionFactory sf=conf.buildSessionFactory( );Session hsession=sf.openSession( );// code to perform DB oparationsTransaction tx=hsession.beginTransaction( );

String vhql="from org.sunil.Employee as e where e.salary>=? and e.salary<=?";Query qry=hsession.createQuery(vhql);qry.setString(0,"20000");qry.setString(1,"40000");List empList=qry.list( );for(int i=0;i<empList.size( );i++){

Object o=empList.get(i);Employee emp=(Employee)o;System.out.println(emp.getEno( ));System.out.println(emp.getEname( ));System.out.println(emp.getAge( ));System.out.println(emp.getSalary( ));

SUDHEER REDDY

89

Min salMax sal

Page 90: J2EE Notes

POTHURAI

System.out.println("-------");}tx.commit( );hsession.close( );

}}

Here ? ---- is called as positional parameter.

HibApp11 Run As Java Application2ETwo2220000.0-------3EThr2330000.0-------4EFour2440000.0-------

We can use the object of type restriction criteria, as part of our application to get the results similar to the above application.

In place of positional parameter, we can use the named parameters to improve the readability of the code.

String vhql="from org.sunil.Employee as e where e.salary>=:minsal and e.salary<=:maxsal";

Query qry=hsession.createQuery(vhql);qry.setString(“minsal”,"20000");qry.setString(“maxsal”,"40000");List empList=qry.list( );// code same as earlier application.

Here minsal & maxsal are called names of the parameters.

Hibernate can automatically manage one-to-one, one-to-many, many-to-one, many-to-many.

The relationship between employee & empaddrs is one-to-many. The relationship between empaddrs & employee is many-to-one. As

shown the figure.

SUDHEER REDDY

90

Page 91: J2EE Notes

POTHURAI

Employee

Empaddrs

SQL> create table employee (eno number(4) primary key, ename varchar(10), age number(3), salary number(10,2));Table created.SQL> create table empaddrs (aid number(4) primary key, empno number(4) references employee(eno), addrno number(1), street varchar(10), city varchar(10));Table created.

Empaddrs

Set Employee

Empaddrs

Get Empaddrs & set Empaddrs is for maintaining The relationship with the Rows of Empaddrs table.

org.sunil.Employee

SUDHEER REDDY

91

eno(PK) ename age salary

1 EOne 21 10000

2 ETwo 22 20000

aid(PK) empno addrno street city

1 1 1 SOne COne 2 1 2 STwo CTwo 3 2 1 Sx Cx 4 2 2 Sy Cy 5 2 3 Sz Cz

1EOne

2110000

Property name Type

eno longename Stringsalary Doubleage Longempaddrs Set

Page 92: J2EE Notes

POTHURAI

Empaddrs Employee

Used to manage the Relationship with employeeData

org.sunil.Empaddrs

Note: - The tags like one-to-many, many-to-one are used in the hbm files to specify the type of relationships that exists between various entities.

package org.sunil;import org.hibernate.*;import org.hibernate.cfg.*;import java.util.*;public class HibApp12 {

public static void main(String[] args)throws Exception {Configuration conf=new Configuration( );conf.configure( );SessionFactory sf=conf.buildSessionFactory( );Session hsession=sf.openSession( );// code to perform DB oparationsTransaction tx=hsession.beginTransaction( );Employee emp=new Employee( );emp.setEno(new Long(1));emp.setEname("EOne");emp.setAge(new Long(21));emp.setSalary(new Double(10000));Empaddrs ea1,ea2;ea1=new Empaddrs( );ea2=new Empaddrs( );ea1.setAid(new Long(1));ea1.setAddrno(new Long(1));ea1.setStreet("SOne");

SUDHEER REDDY

92

11

SOneCOne

1EOne

2110000

Property name Type

aid Longaddrno Longstreet StringCity Stringemployee Employee

Page 93: J2EE Notes

POTHURAI

ea1.setCity("COne");ea2.setAid(new Long(2));ea2.setAddrno(new Long(2));ea2.setStreet("STwo"); ea2.setCity("CTwo");ea1.setEmployee(emp);ea2.setEmployee(emp);Set eaSet=new HashSet( );eaSet.add(ea1); eaSet.add(ea2);emp.setEmpaddrses(eaSet);hsession.save(emp);tx.commit( );hsession.close( );

}}

HibApp12 Run As Java ApplicationSQL> select * from employee; ENO ENAME AGE SALARY-------------- ---------- ------------------ ---------------- 1 EOne 21 10000SQL> select * from empaddrs;no rows selected

As part of the employee.hbm.xml file, if we specify cascade=“all” or cascade=“save-update”, hibernate stores the data in employee table & empaddrs table when the above application will be save.

<set name="empaddrses" inverse="true" cascade="all">inverse= “true” --- is to tell that the relationship must be maintained from both sides.

HibApp12 Run As Java ApplicationSQL> select * from employee; ENO ENAME AGE SALARY------------ ----------------- ------------- ------------------- 1 EOne 21 10000SQL> select * from empaddrs; AID EMPNO ADDRNO STREET CITY---------- ---------- ---------- ---------- --------------- ------------- 2 1 2 STwo CTwo 1 1 1 SOne Cone

SQL> select * from employee; ENO ENAME AGE SALARY---------- ---------- ---------- ---------------- -------------- 1 EOne 21 10000 2 ETwo 22 20000

SUDHEER REDDY

93

Page 94: J2EE Notes

POTHURAI

** What is lazy fetching & immediate / eager / aggressive fetching?A) package org.sunil;

import org.hibernate.*;import org.hibernate.cfg.*;import java.util.*;public class HibApp13 {

public static void main(String[] args)throws Exception {Configuration conf=new Configuration( );conf.configure( );SessionFactory sf=conf.buildSessionFactory( );Session hsession=sf.openSession( );// code to perform DB oparationsTransaction tx=hsession.beginTransaction( );String vhql="from org.sunil.Employee";Query qry=hsession.createQuery(vhql);System.in.read( );System.in.read( );System.out.println("----qry list executed----");List empList=qry.list( ); for(int i=0;i<empList.size( );i++){

Employee emp=(Employee)empList.get(i);System.out.print("\t"+emp.getEno( ));System.out.print("\t"+emp.getEname( ));System.out.print("\t"+emp.getAge( ));System.out.println("\t"+emp.getSalary( ));Set eaSet=emp.getEmpaddrses( );;Iterator it=eaSet.iterator( );while(it.hasNext( )){

Empaddrs ea=(Empaddrs)it.next( );System.out.println("----calling get City----");System.out.println(ea.getCity( ));

}}tx.commit( );hsession.close( );

}}

The above application requires the data available in Employee table only. Most of the applications are like the above application (that is most of the applications may be accessing the data in the main table but not associated data in the other tables).

HibApp13 Run As Java Application----qry list executed----

3 EThr 23 30000.01 EOne 21 10000.0

----calling get City----COne

SUDHEER REDDY

94

Page 95: J2EE Notes

POTHURAI

----calling get City----CTwo

2 ETwo 22 20000.04 EFour 24 40000.0

If aggressive loading strategy is used hibernate loads the data from employee table & empaddrs table when qry.list( ) is executed. In case of the above application hibernate waste time by loading the data from empaddrs table.Note: - For using immediate loading the following tag must be used in employee.hbm.xml.<set name="empaddrses" inverse="true" cascade="all" lazy="true">

If lazy=“true” is used hibernate uses lazy loading strategy. In this case hibernate gets the data from employee table only when qry.list( ) executed.

When lazy loading is used hibernate to loads the data from the associated table only, if it is required / accessed.

Most of the application will be benefited by lazy loading strategy.

A design pattern is a good solution for re-occurring problem.

Singleton design pattern: - Maintain only one object based on a class is called as singleton.

As it is not recommended to repeatedly call configure( ) method & buildSessionFactory( ) method. It is recommended to maintain one instance (singleton) of SessionFactory. We can use the class shown below for maintaining a singleton of type SessionFactory.

We can use the code shown below to deal with the database using Hibernate.Session hsession=org.sunil.OraSF.currentSession( );// code to deal with DBorg.sunil.OraSF.closeSession( );

Note: - org.sunil.OraSF is a class generated by MyEclipse IDE. The internal code of this class maintains a singleton of type SessionFactory.

import org.hibernate.*;import org.hibernate.cfg.*;public class HibUtil {

private static SessionFactory sf=null;static {

try{

Configuration conf=new Configuration( );conf.configure( );sf=conf.buildSessionFactory( );

}catch (Exception e) { }public static SessionFactory getSf( ) {

return sf;

SUDHEER REDDY

95

Page 96: J2EE Notes

POTHURAI

}}

}

public class Employee{private satatic Employee emp=null;static {

emp=new Employee( );}public static Employee createEmp( ) {

return emp;}

}(or)

public class Employee{private satatic Employee emp=null;public static Employee createEmp( ) {

if(emp=null) {emp=new Employee( );

}return emp;

}}

JNDI: - (java naming and directory interface).JNDI API can be used to access the directory servers

A directory server can be used to manage the data like a database server. A directory server does not support SQL.

Directory servers are optimized for search operations (that is a directory server is fast in performing search operations compared to database servers.) directory servers are used by the applications that has to perform search operations frequently.Ex: - yahoo, Bigfoot, who where, uses LDAP (light weight directory protocol) server to maintain the information about people.

There are various directory servers available in market. Some of them are LDAP, Active directory server (ADS from Microsoft), NDS (novel directory server from novel).

Directory services are provided as part of servers like web logic, web sphere, jboss etc ….

SUDHEER REDDY

96

Store data (insert)Delete data (delete)

Modify data (update)Find data (select)

Java App using JDBC API Java App using JNDI API

Database server Directory server

Page 97: J2EE Notes

POTHURAI

Java enterprise edition (JEE) is an open speciation & it can be implemented by any one. The servers like web logic, web sphere, jboss, sun one server, Oracle Application server …. etc are implemented according to JEE specification & all these servers provides various facilities like hosting the web applications, hosting the EJB’S, managing the transactions using JTA (java transaction API) etc …..

Web logic provides directory service.Procedure for setting up web logic server: - (www.bea.com)Steps: - 1) Start domain configuration wizardStart programs bea configuration wizard.

2) Click on next button

3) Choose basic web logic server domain & click on next

SUDHEER REDDY

97

Page 98: J2EE Notes

POTHURAI

4) Click on next button.

5) Provide username (web logic) ,password (chennakesava) & click on next button.

6) Click next button.

7) Provide the configuration name (student) & click on create button

8) Click on Done button.Note: - configuration wizard creates a directory with the name student under C:\bea\user_projects\domains\ directory & copies various files & directories in the student directory.C:\bea\user_projects\domains\student>startweblogicWeb logic uses 7001 as it port number by default.

SUDHEER REDDY

98

Page 99: J2EE Notes

POTHURAI

Browser Web logic server, jboss, web sphere etc

An application must establish a connection with DB to Access DB using JDBC API. An application must establish a connection with Dir server to access Dir server using JNDI API.

In order to deal with the directory servers, an application must get the reference of (class name) initial Context object.

A set of properties must be used to get the reference of initial Context object. We can get the information about these properties from the documentation provided by JNDI implementation.

jndi.properties: - java.naming.provider.url=t3://localhost:7001/java.naming.security.principal=weblogicjava.naming.security.credentials=chennakesavajava.naming.factory.initial=weblogic.jndi.WLInitialContextFactory

Save: - jndi.properties

import javax.naming.*;import java.util.*;import java.io.*;public class JndiCli{

public static void main(String[] args) throws Exception{

FileInputStream fis=new FileInputStream("jndi.properties");Properties props=new Properties( );System.out.println("---1---"+props);props.load(fis);System.out.println("---2---"+props);Context ic=new InitialContext(props);System.out.println("---got ic---");

}}

D:\psr\J2EE>javac JndiCli.java

SUDHEER REDDY

99

……..

http://localhost:7001/consoleDir service

Web container

EJB container

Page 100: J2EE Notes

POTHURAI

D:\psr\J2EE>java JndiCliException in thread "main" javax.naming.NoInitialContextException: Cannot instantiate class: weblogic.jndi.WLInitialContextFactory [Root exception is java.lang.ClassNotFoundException: weblogic.jndi.WLInitialContextFactory] Caused by: java.lang.ClassNotFoundException:

weblogic.jndi.WLInitialContextFactory ... 5 more

C:\bea\user_projects\domains\student>setenvC:\bea\user_projects\domains\student>d:D:\>cd psrD:\psr>cd j2eeD:\psr\J2EE>set CLASSPATH=%CLASSPATH%;.D:\psr\J2EE>javac JndiCli.javaD:\psr\J2EE>java JndiCli---1---{}---2---{java.naming.factory.initial=weblogic.jndi.WLInitialContextFactory, java.naming.provider.url=t3://localhost:7001/, java.naming.security.principal=weblogic, java.naming.security.credentials=chennakesava}---got ic---

We can configure various services of web logic server using web logic console.To access web logic console: -Steps: - 1) Start the browser.2) Type the url (http://localhost:7001/console)

3) Provide the user name, password & click on sign in button

SUDHEER REDDY

100

Page 101: J2EE Notes

POTHURAI

To check what is available in the directory service of web logic: - 1) Choose servers myServer

2) Right click on myServer to get a popup menu

SUDHEER REDDY

101

Page 102: J2EE Notes

POTHURAI

3) Choose view JNDI tree.

Initial Context

Sub Context

Bound objects

Most of the directory servers support tree structure for organizing the information as shown in the diagram. The starting point is called as initial Context. Under initial Context we can have bound objects & sub contexts. Note: -The objects that can be stored in the directory server must be Serializable.

We can create the sub context mbatch & ebatch as shown below. import javax.naming.*;import java.util.*;import java.io.*;

SUDHEER REDDY

102

mbatch

ebatch

none

ntwo

nxxx

nzzz

Page 103: J2EE Notes

POTHURAI

public class CSContext1{

public static void main(String[] args) throws Exception{

FileInputStream fis=new FileInputStream("jndi.properties");Properties props=new Properties( );props.load(fis);Context ic=new InitialContext(props);ic.createSubcontext("mbatch");ic.createSubcontext("cbatch");

}}

D:\psr\J2EE>javac CSContext1.javaD:\psr\J2EE>java CSContext1

Sub Context

The above structure can be created using the code shown belowimport javax.naming.*;import java.util.*;import java.io.*;public class CSContext2{

public static void main(String[] args) throws Exception

SUDHEER REDDY

103

mbatch

female

male

Page 104: J2EE Notes

POTHURAI

{FileInputStream fis=new FileInputStream("jndi.properties");Properties props=new Properties( );props.load(fis);Context ic=new InitialContext(props);ic.createSubcontext("mbatch");ic.createSubcontext("mbatch/female"); // ( / means path separator)ic.createSubcontext("mbatch/male");

}}

D:\psr\J2EE>javac CSContext2.javaD:\psr\J2EE>java CSContext2

The context created by the code shown above & can be removed the code shown belowimport javax.naming.*;import java.util.*;import java.io.*;public class DCSContext{

public static void main(String[] args) throws Exception{

FileInputStream fis=new FileInputStream("jndi.properties");Properties props=new Properties( );props.load(fis);Context ic=new InitialContext(props);ic.destroySubcontext("mbatch/female");ic.destroySubcontext("mbatch/male");ic.destroySubcontext("mbatch");

}}D:\psr\J2EE>javac DCSContext.javaD:\psr\J2EE>java DCSContext

SUDHEER REDDY

104

Page 105: J2EE Notes

POTHURAI

We can use the bind method to store a java object in the directory serverimport javax.naming.*;import java.util.*;import java.io.*;public class BindMethod1{

public static void main(String[] args) throws Exception{

FileInputStream fis=new FileInputStream("jndi.properties");Properties props=new Properties( );props.load(fis);Context ic=new InitialContext(props);Integer o1=new Integer(111);Long o2=new Long(222);String o3=new String("333");ic.bind("objone",o1);ic.bind("objtwo",o2);ic.bind("objthr",o3);

}}D:\psr\J2EE>javac BindMethod1.javaD:\psr\J2EE>java BindMethod1

SUDHEER REDDY

105

Page 106: J2EE Notes

POTHURAI

To remove the objects from the directory server we can use unbind method.import javax.naming.*;import java.util.*;import java.io.*;public class BindMethod2{

public static void main(String[] args) throws Exception{

FileInputStream fis=new FileInputStream("jndi.properties");Properties props=new Properties( );props.load(fis);Context ic=new InitialContext(props);ic.unbind("objone");ic.unbind("objtwo");ic.unbind("objthr");

}}

D:\psr\J2EE>javac BindMethod2.javaD:\psr\J2EE>java BindMethod2

To replace an existing object rebind method can be usedimport javax.naming.*;import java.util.*;import java.io.*;public class BindMethod3{

public static void main(String[] args) throws Exception{

FileInputStream fis=new FileInputStream("jndi.properties");Properties props=new Properties( );props.load(fis);Context ic=new InitialContext(props);Integer i=new Integer(100);

SUDHEER REDDY

106

Page 107: J2EE Notes

POTHURAI

Float f=new Float(200.002);ic.bind("objOne",i);// ic.bind("objOne",f); // error (NameAlreadyBoundException) ic.rebind("objOne",f);

}}

D:\psr\J2EE>javac BindMethod3.javaD:\psr\J2EE>java BindMethod3

import javax.naming.*;import java.util.*;import java.io.*;public class BindMethod4{

public static void main(String[] args) throws Exception{

FileInputStream fis=new FileInputStream("jndi.properties");Properties props=new Properties( );props.load(fis);Context ic=new InitialContext(props);ic.createSubcontext("scone");ic.createSubcontext("scone/sctwo");Integer o1=new Integer(111);Long o2=new Long(222);String o3=new String("333");ic.bind("objone",o1);ic.bind("scone/objtwo",o2);ic.bind("scone/sctwo/objthr",o3);

}}

D:\psr\J2EE>javac BindMethod4.javaD:\psr\J2EE>java BindMethod4

SUDHEER REDDY

107

Page 108: J2EE Notes

POTHURAI

To get an object from the directory server lookup method can be used.import javax.naming.*;import java.util.*;import java.io.*;public class LookUp1{

public static void main(String[] args) throws Exception{

FileInputStream fis=new FileInputStream("jndi.properties");Properties props=new Properties( );props.load(fis);Context ic=new InitialContext(props);Object o=ic.lookup("objone");System.out.println(o.getClass( ));

}}

D:\psr\J2EE>javac LookUp1.javaD:\psr\J2EE>java LookUp1class java.lang.Integer

import javax.naming.*;import java.util.*;import java.io.*;public class LookUp2{

public static void main(String[] args) throws Exception{

FileInputStream fis=new FileInputStream("jndi.properties");Properties props=new Properties( );props.load(fis);Context ic=new InitialContext(props);

SUDHEER REDDY

108

Page 109: J2EE Notes

POTHURAI

Object o=ic.lookup("objone");Integer i=(Integer)o;System.out.println(i.getClass( ));o=ic.lookup("scone/objtwo");Long l=(Long)o;System.out.println(l.getClass( ));o=ic.lookup("scone/sctwo/objthr");String s=(String)o;System.out.println(s.getClass( ));

}}

D:\psr\J2EE>javac LookUp2.javaD:\psr\J2EE>java LookUp2class java.lang.Integerclass java.lang.Longclass java.lang.String

Object pooling: - A group of objects is called as a pool of objects. Object pooling technique is used mainly to deal with the objects that are expensive to create. An application using object pooling technique follows the steps given below. 1) An application creates n number of objects & places this objects in the pool (assume n =5)2) If the application has to use an object it picks up the object from the pool, uses the object returns the object of the pool (The object that is return to the pool can be reuse)3) At any point of time of the number of objects available in the pool are not enough the application can add few of more object to the pool. This is called as expanding the pool.4) If there are more objects in the pool (100), but most of the time a maximum pf 10 objects are used when the application can remove up to 90 objects from the pool. This is called as shrinking the pool.

DriverManager.getConnection method establishes the connection with the server & creates a connection objects. This operation is expensive (takes more amount of time). When a connection is created using DriverManager.getConnection calling con.close( ) closes the connection. As the creation of connection object is expensive it is recommended to use connection pooling technique?

import java.sql.*;public class Sql{

public static void main(String[] args) throws Exception{

SUDHEER REDDY

109

Page 110: J2EE Notes

POTHURAI

long t1,t2;t1=System.currentTimeMillis( );Class.forName("oracle.jdbc.driver.OracleDriver");Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","sunil");t2=System.currentTimeMillis( );System.out.println(t2-t1);

}}

D:\psr\J2EE>javac Sql.javaD:\psr\J2EE>java Sql484D:\psr\J2EE>java Sql437

The J2EE servers like web logic, JBOSS, web sphere etc. manages the connection pools on their own.

Procedure for setting up the connection pool in web logic:-1) Login to web logic console.2) Choose services JDBC connection pools & click on configure a new JDBC connection pool.

3) Choose oracle as Database type, oracle’s Driver (thin) as Database Driver & click on continue button.

SUDHEER REDDY

110

Page 111: J2EE Notes

POTHURAI

4) Provide the following information and click on continue button.

5) Click on Test Driver configuration button.

SUDHEER REDDY

111

Page 112: J2EE Notes

POTHURAI

6) Click on create and deploy button.

Connection pools orapool & Provide the following information and click on Apply button.

SUDHEER REDDY

112

Page 113: J2EE Notes

POTHURAI

Java App

Web logicProcedure to setup data source object: - 1) Choose services JDBC Data Sources & click on configure a new JDBC data source.

2) Provide name (dsone), JNDI name (org/students/orads) & click on continue button.

SUDHEER REDDY

113

DB

Data Source

orapool

Dir Srvorg/Student/orads

Page 114: J2EE Notes

POTHURAI

3) Choose orapool as pool name & click on continue button

4) Click on create button

import javax.naming.*;import java.util.*;import java.io.*;import java.sql.*;import javax.sql.*;public class DataSourceMethod{

public static void main(String[] args) throws Exception{

// code to get Initial ContextFileInputStream fis=new FileInputStream("jndi.properties");Properties props=new Properties( );props.load(fis);Context ic=new InitialContext(props);Object o=ic.lookup("org/students/orads");DataSource ds=(DataSource)o;Connection con=ds.getConnection( ); 1//code to perform DB oparationscon.close( ); 2

}}

1 ds.getConnection( ) gets the connection from connection pool.2 con.close( ) returns connection to connection pool.Note: - Using the connection pool maintained 5 web logic servers from a web application; EJB application improves the performance of the applications.

SUDHEER REDDY

114

Page 115: J2EE Notes

POTHURAI

Note: - Hibernate uses a connection from the connection pool for improving the performance of the application. Hibernate picks up the connection from the connection pool when it has to perform the database operations & returns the connection to the connection pool when the close( ) method is called. Web server is a product that supports HTTP (hyper text transfer protocol). A web client can communicate with the web server using HTTP. A web client sends some data to ask the web server to perform some operations. This data is called as request. After receiving the request the server performs the operation & sends some data to the web client. This data will call as response.

Request

Response

Web server, Microsoft iis, apache browser, internet Explorer web server ----- etc opera, Netscape etc ….

Copy the HWebServer1.java file into psr/j2ee folder.C:\bea\user_projects\domains\student>setenvD:\psr\J2EE>set CLASSPATH=%CLASSPATH%;.D:\psr\J2EE>javac HWebServer1.javaD:\psr\J2EE>java HWebServer1 8000logging to stdoutroot=D:\psr\J2EEtimeout=5000workers=5©

<html> <head> <title> One.html </title> <head> <body> This is One.html body </body></html>Open the browser & type the url http://localhost:8000/One.html This is One.html body© ...GET /One.html HTTP/1.1Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*Accept-Language: en-usAccept-Encoding: gzip, deflateUser-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)Host: localhost:8000Connection: Keep-AliveFrom 127.0.0.1: GET D:\psr\J2EE\One.html-->200

SUDHEER REDDY

115

Page 116: J2EE Notes

POTHURAI

HTTP protocol: - 1) The client establishes the connection with the server.2) The client sends a request to the server.3) The server process the request.4) The server sends the response to the client.

HTTP protocol specifies that line must be terminated using \r\n (enter key). According to HTTP protocol the client must send the request using the format shown below.

HTTP REQUEST FORMAT

Format of IRQ

Ex: -

Format of HEADER LINE

Ex: -

is os

get the data send the data

Socket

SUDHEER REDDY

116

Initial request line

N no of HEADER LINES

Blank line

REQUEST BODY (optional)

REQUEST METHOD REQUESTED URI PROTO/VER

GET /One.html HTTP/1.1

HEADER NAME: HEADER VALUE

User-Agent: Our browser 1.0

Page 117: J2EE Notes

POTHURAI

The format of response is similar to the format of request.

HTTP RESPONSE FORMAT

Format of initial Response line

Ex: -

import java.io.*;import java.net.*;public class WebCli{

public static void main(String[] args) throws Exception{

int port=8000;InetAddress ia=InetAddress.getByName("localhost");Socket sock=new Socket(ia,port);System.out.println("---Connected to server---");String sreq="GET /One.html HTTP/1.0 \r\n User-Agent:Our Own Browser 1.0 \r\n\r\n"; ®InputStream sis=sock.getInputStream( );OutputStream sos=sock.getOutputStream( );PrintStream ps=new PrintStream(sos);ps.print(sreq); // send requestSystem.out.println("---Sent Server---");System.in.read( );System.in.read( );System.out.println("---RESPONSE---");byte bresp[]=new byte[3000];int nob=sis.read(bresp,0,3000); // get responseString sresp=new String(bresp,0,nob);System.out.println(sresp);

}}

SUDHEER REDDY

117

Initial response line

N no of HEADER LINES

Blank line

RESPONSE BODY (optional)

PROTO/VER STATUS CODE STATUS USER

HTTP/1.1 200 OK

Page 118: J2EE Notes

POTHURAI

D:\psr\J2EE>javac WebCli.javaD:\psr\J2EE>java WebCli---Connected to server------Sent Server---

---RESPONSE---HTTP/1.0 200 OKServer: Simple javaDate: Fri Sep 28 16:07:49 IST 2007Content-length: 109Last Modified: Wed Sep 26 13:59:57 IST 2007Content-type: text/html

<html> <head> <title> One.html </title> <head> <body> This is One.html body </body></html>

© ...GET /One.html HTTP/1.0 User-Agent: Our Own Browser 1.0

From 127.0.0.1: GET D:\psr\J2EE\One.html-->200

® String sreq="HEAD /One.html HTTP/1.0 \r\n User-Agent: Our Own Browser 1.0 \r\n\r\n";

D:\psr\J2EE>javac WebCli.javaD:\psr\J2EE>java WebCliHTTP/1.0 200 OKServer: Simple javaDate: Fri Sep 28 16:14:01 IST 2007Content-length: 109Last Modified: Wed Sep 26 13:59:57 IST 2007Content-type: text/html

© ...HEAD /One.html HTTP/1.0 User-Agent: Our Own Browser 1.0

From 127.0.0.1: GET D:\psr\J2EE\One.html-->200

What is the difference between HEAD request method and GET request method?A) When the client sends GET Request, the server sends the response with initial request line, header lines, response body to the client.

SUDHEER REDDY

118

Page 119: J2EE Notes

POTHURAI

If the client sends HEAD Request, the server sends the response with initial response line, n no of headers to the client (i.e the body will not sent to the client as part of the response).

When the server sends a response, Content-Type Header will be sent to indicate what kind of content is provided as part of the body.Ex: - Content-Type: text/html

Content-Type: text/xmlContent-Type: image/bmp

Note: - As part of MIME (multimedia internet mail extension) various kinds of contents are provided. Some of them are text/html, text/xml, text/plain, image/gif, image/bmp etc…. Text, images are called as main types. Plain, xml, html, bmp are called as sub types.Sudheer.doc Content-Type: application/msword.

HTTP protocol as specify various numbers that can be used as status codes.1xx --- information messages2xx --- Success3xx --- redirect4xx --- Error due to client5xx --- Error due to Server

DELETE request method can be used by the clients to request the server to delete a resource. The servos are setup not to allow the delete request method.

® String sreq="DELETE /One.html HTTP/1.0 \r\n User-Agent: Our Own Browser 1.0 \r\n\r\n";

D:\psr\J2EE>javac WebCli.javaD:\psr\J2EE>java WebCli---Connected to server------Sent Server---

---RESPONSE---HTTP/1.0 405 unsupported method type: DELET© ...DELETE /One.html HTTP/1.0 User-Agent: Our Own Browser 1.0

unsupported method

PUT can be used by the client to put a resource (file) on the server. By default this is not allowed.

When the client sends the OPTIONS request method, the server send the response with allow header providing the information about the request methods that are allowed by the server.

SUDHEER REDDY

119

Page 120: J2EE Notes

POTHURAI

TRACE request method can be used to diagnolize (check) the problems if the server.

The browser mainly uses GET, POST, HEAD request methods while interacting with the web servers.

To develop web applications that generates the content dynamically, we can use the technologies like common gateway (CGI), Active server pages (ASP), Servlet/JSP etc…

Java soft has designed Servlet technology & it is an Open specification. Any one can provide the server supporting Servlet technology according to java soft. A server that supports Servlet technology is called as Web Container. Some of the popular products that support Servlet technology are Apache Tomcat, Web logic, web sphere, Oracle application Server, Sun one network etc….

JDBC, ODBC are part of J2SE. Hibernate is not part of J2SE & J2EE. It is allow only J2SE, J2EE applications.

P. Sunil Kumar Reddy

SUDHEER REDDY

120