Sie sind auf Seite 1von 119

1 POTHURAI

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

java.lang.Object String toString( ) int hashCode( ) ..


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.

java.lang.Object String toString( ) int hashCode( ) ..


extends

Cone void mone( ) Cone( ) added by the compiler


public class Cone1 SUDHEER REDDY

2 POTHURAI { public Cone1(int i) { // System.out.println("------Cone1(int i)------"); } public void mone( ) { // System.out.println("------Cone1:mone------"); } } D:\psr\J2EE>javac Cone1.java D:\psr\J2EE>javap Cone1 Compiled 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.

Person setName(String name) String getName( )


extends extends

Student setFee(float fee) float getFee( )

Teacher setSal(float sal) float getSal( )

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

3 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.java D:\psr\J2EE>java App Cone@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.java D:\psr\J2EE>java App -----Ctwo:toString( )----Sudheer SUDHEER REDDY

4 POTHURAI

java.lang.Object String toString( ) returns clsName@ hash code


extends

ClsOne toString( ) not found


extends

ClsTwo String toString( ) { return Sunil};


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( ); 1 o.toString( ); 2 System.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( ); 1 o.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

5 POTHURAI this.empName=EmpName; this.salary=salary; } -------} Emp c1=new Emp(1,"EOne",10000.001f); Emp c2=new Emp(2,"ETwo",20000.002f); c1

1 EOne 100000.001

Emp

c2

2 ETwo 200000.002

Emp

Emp obj is for holding details of an Emp Student obj for holding details of a Student Class 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

Info about String class Info about Date class

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 JVMS memory, this process is called as class loading. public class Appli { public static void main(String[] args) throws Exception { SUDHEER REDDY

6 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.java D:\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.java D:\psr\J2EE>java Appli java.lang.String package java.lang, java platform API specification, version 1.5 The above application always loads the same class (java.lang.String). java -Dspone =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

7 POTHURAI D:\psr\J2EE>javac Applications.java D:\psr\J2EE>java Applications null null D:\psr\J2EE>java -Dspone=xyz Dsptwo=abc Applications xyz abc 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.java D:\psr\J2EE>java Dclsname=java.net.Socket AApplications java.net.Socket java.net.Socket package java.net, java platform API specification, version 1.5 D:\psr\J2EE>java Dclsname= java.util.Vector AApplications java.util.Vector java.util.Vector package 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

8 POTHURAI set CLASSPATH= . : ; C:\xyz; log4j-1.2.8.jar Current directory Environment variable Command in dos javap org.apache.log4j.Appender Name of the interface 1) 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.jar Linux / 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 ConsoleAppender Logger RootLogger SUDHEER REDDY DEBUG - --msg one

9 POTHURAI D:\psr\J2EE> set CLASSPATH=.; log4j-1.2.8.jar D:\psr\J2EE>javac Log.java D:\psr\J2EE>java Log DEBUG - --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.java D:\psr\J2EE>java Log4j DEBUG - --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); logger.addAppender(appender2); SUDHEER REDDY

10 POTHURAI 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.java D:\psr\J2EE>java Log4j1 Log session start time Mon Aug 27 12:45:32 IST 2007 Time 0 31 47 47 62 Thread main main main main main Level DEBUG INFO WARN ERROR FATAL Category root root root root root Message --msg one ---msg two ---msg three ---msg four ---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.java D:\psr\J2EE>java Log4j2 WARN - --msg three -ERROR - --msg four -FATAL - --msg five

SUDHEER REDDY

11 POTHURAI 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, A1 log4j.appender.A1=org.apache.log4j.ConsoleAppender log4j.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.java D:\psr\J2EE>java Log4j3 ERROR - --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

12 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"); 1 Class cls=Class.forName(vclsname); 2 Object o=cls.newInstance( ); 3 System.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

Info about CThr class


java.lang.Class object

3 When newInstance( ) method executed, it will create an object of type CThr using the zero argument constructor of CThr class. SUDHEER REDDY

13 POTHURAI 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.java D:\psr\J2EE>java Dclsname= CThr AApp ---CThr created--o-->class CThr D:\psr\J2EE>java Dclsname= CFour AApp o-->class CFour D:\psr\J2EE>java Dclsname= CFive AApp Exception 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.

NTBC

(I mean) Prefix of interface

IBillCalculator float calcBill(String cid,int nocu);


implements implements

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 }

SUDHEER REDDY

14 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.java D:\psr\J2EE>java Dclsname=Student TBApp Exception 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 airtel System.out.println("----AIRTEL----"); float billAmt=100; int utc=nocu-200; if(utc>0) { SUDHEER REDDY

15 POTHURAI 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( ); 1 IBillCalculator bc; bc=(IBillCalculator)o; 2 System.out.println("------tc successful------"); float ba=bc.calcBill("xyz",400); 3 System.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 { public float calcBill(String cid,int nocu) { SUDHEER REDDY

16 POTHURAI // code to caluclate bill all to airtel System.out.println("----HUTCH----"); float billAmt=100; int utc=nocu-225; if(utc>0) { billAmt+=(utc*1.25); } return billAmt; } } D:\psr\J2EE>javac HBillCalculator.java TBApp 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 NTBC System.out.println("----NT----"); float billAmt=0; billAmt+=nocu * 0.75; return billAmt; } } D:\psr\J2EE>javac NTBC.java D:\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. 1) We can declare a reference variable of type interface, but we can not create an object based on interface. IBillCalculator bc; SUDHEER REDDY

17 POTHURAI 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 APIS, 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 APIS. A set of APIS like jdbc, jndi, AWT/WING, networking API etc are part of java standard edition. JEE is a combination of APIS 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.

ip196.12.100.1 port1521 service namexe


Oracle server

Connection object
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 { Connection con; con=new oracleDriver( ); System.out.println(------Connected------); } SUDHEER REDDY

18 POTHURAI } D:\psr\J2EE>javac Jdbc.java D:\psr\J2EE>java Jdbc Jdbc.java:7: cannot find symbol symbol : class oracleDriver location: class Jdbc con=new oracleDriver( ); ^ 1 error D:\psr\J2EE> set CLASSPATH=ojdbc14.jar;. D:\psr\J2EE>java Jdbc -----Connected------

java.sql.Connection provide java soft

oracle.jdbc.oracleConnetion provided by Oracle

oracle.jdbc.internal.Connetion provided by Oracle

oracle.jdbc.driver.oracleDriver provided by Oracle

java.sql.Driver provide java soft

oracle.jdbc.driver.oracleDriver provided by Oracle


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. SUDHEER REDDY

19 POTHURAI 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.

java.sql.Driver --- Connection --- Statement Interfaces provided

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

by java soft
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.java D:\psr\J2EE>java OraApp --- Connected -->class oracle.jdbc.driver.T4CConnection import java.sql.*; public class MyApp { public static void main(String[] args) throws Exception { Driver drv=new com.mysql.jdbc.Driver( ); DriverManager.registerDriver(drv); Connection con=DriverManager.getConnection ("jdbc:mysql://localhost:3306/test"," "," "); SUDHEER REDDY

20 POTHURAI 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.java D:\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); } } 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?: -

SUDHEER REDDY

21 POTHURAI 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.

Create .. Connection Statement


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.java D:\psr\J2EE>java DBApp SQL> desc employee; Name Null? Type ----------------------------------------- -------- ---------------------------EMPNAME VARCHAR2(10) EMPNO NUMBER(3) SALARY NUMBER(10,2) 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.

SUDHEER REDDY

22 POTHURAI 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).

Empname: Empno: Salary:

EOne 1 10000

Store emp
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 selected SQL> commit; Commit complete. import java.sql.*; public class SDBApp { 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 DB Statement stmt=con.createStatement( ); SUDHEER REDDY

23 POTHURAI 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.java D:\psr\J2EE>java SDBApp SQL> select * from employee; EMPNAME EMPNO SALARY ---------- ---------- --------------------- ------------EOne 1 10000 ETwo 2 20000 EXyz 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. Parameters Place 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 DB String vsql="insert into employee values(?,?,?)"; PreparedStatement pstmt=con. prepareStatement(vsql); pstmt.setString(1,"EOne"); pstmt.setInt(2,1); pstmt.setFloat(3,10000); pstmt.executeUpdate( ); pstmt.setString(1,"ETwo"); SUDHEER REDDY

24 POTHURAI 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.java D:\psr\J2EE>java PSDBApp SQL> select * from employee; EMPNAME EMPNO SALARY ---------- ---------- --------------------- ------------EOne 1 10000 ETwo 2 20000 EXyz 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 DB String vsql="delete from employee where empno=?"; PreparedStatement pstmt=con.prepareStatement(vsql); pstmt.setInt(1,1); pstmt.executeUpdate( ); pstmt.setInt(1,2); pstmt.executeUpdate( ); pstmt.setInt(1,200); pstmt.executeUpdate( ); } } SUDHEER REDDY

25 POTHURAI D:\psr\J2EE>javac DDBApp.java D:\psr\J2EE>java DDBApp SQL> 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 2 EXyz 200 10000 EOne 1 1 SQL> 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 DB String 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"); pstmt.setString(2,"1"); pstmt.executeUpdate( );; } } SUDHEER REDDY

26 POTHURAI D:\psr\J2EE>javac StDBApp.java D:\psr\J2EE>java StDBApp SQL> select * from employee; EMPNAME EMPNO SALARY ---------- ---------- ----------- -----------------ETwo 2 50000 EXyz 200 60000 EOne 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 employee Ex: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.java D:\psr\J2EE>java DeDBApp ------nore----->3 SQL> 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. import java.sql.*; public class DeDBApp { public static void main(String args[]) throws Exception SUDHEER REDDY

27 POTHURAI { 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.java D:\psr\J2EE>java DeDBApp ------nore----->0 SQL> 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( )); rs.next( ); System.out.println(rs.getRow( )); rs.next( ); System.out.println(rs.getRow( )); SUDHEER REDDY

28 POTHURAI rs.next( ); } } D:\psr\J2EE>javac RSDBApp.java D:\psr\J2EE>java RSDBApp --cur row -->0 1 2 3 0 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.

Employee

empno.

ResultSet
Java DBApp Database 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")); System.in.read( ); System.in.read( ); } } } SUDHEER REDDY

29 POTHURAI D:\psr\J2EE>javac RSDBApp.java D:\psr\J2EE>java RSDBApp --cur row -->1 1 EOne 10000.0 --cur row -->2 2 ETwo 20000.0 --cur row -->3 3 EThr 30000.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")); System.out.println(rs.getString("ename")); System.out.println(rs.getFloat("salary")); } } D:\psr\J2EE>javac RSSDBApp.java SUDHEER REDDY

30 POTHURAI D:\psr\J2EE>java RSSDBApp --about read 3rd row-3 EThr 30000.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.java D:\psr\J2EE>java RSUDBApp SQL> 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. import java.sql.*; public class RSDDBApp { public static void main(String args[]) throws Exception { SUDHEER REDDY

31 POTHURAI 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.java D:\psr\J2EE>java RSDDBApp SQL> 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"); rs.insertRow( ); } } D:\psr\J2EE>javac RSIDBApp.java SUDHEER REDDY

32 POTHURAI D:\psr\J2EE>java RSIDBApp SQL> select * from employee2; EMPNO ENAME SALARY ---------- ---------- ---------- -------------------1 EOne 10000 3 Sunil 25000 100 Sudheer 12345 Employee

empno

ename

salary

Empaddress

empno

street

city

state

Employee empno: salary: Addresses street stone sttwo

100 12345

ename:

Sunil

city
cone ctwo Store

state
sone stwop

Transactions: insert into employee values (100,Sunil,12345); insert into empaddrs values (100,Stone,cone,sone); insert into empaddrs values (100,Sttwo,ctwo,stwo); 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.

SUDHEER REDDY

33 POTHURAI 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 selected SQL> 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')"; con.setAutoCommit(false); try { stmt.executeUpdate(vsql1); SUDHEER REDDY

34 POTHURAI 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.java D:\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 12345 SQL> 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( ); 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); SUDHEER REDDY

35 POTHURAI 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.java D:\psr\J2EE>java TADBApp SQL> select * from employee; ENO ENAME SALARY ---------- ---------- ---------- -----------100 Sunil 12345 101 Sudheer 12346 SQL> select * from empaddrs; ENO STREET CITY STATE ---------- ---------- ---------- ---------- ----------------100 stone cone sone 100 sttwo ctwo stwo 101 stone cone sone 101 sttwo ctwo stwo

tax rates min max tr spcalcx ..


Data base

name tot inc

name

1,50,000

Clac tax
Java App

Most of the database servers support the stored procedures. Sps 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.

SUDHEER REDDY

36 POTHURAI create or replace PROCEDURE ProcOne as i number; BEGIN data type i:=44+11; insert into mytab values (100,i); END ProcOne; / SQL> @ d:\psr\sql\CreProc1.sql; Procedure created SQL> create table mytab (COne number , CTwo number); Table created. SQL> desc mytab; Name Null? Type ----------------------------------------- -------- -------CONE NUMBER CTWO NUMBER SQL> select * from mytab; no rows selected We can use the code shown below to invoke proc1 import 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.java D:\psr\J2EE>java P1Sql SQL> select * from mytab; CONE CTWO ------------------- ---------100 55 create or replace PROCEDURE ProcTwo (pone IN number,ptwo IN number) as BEGIN insert into mytab values (pone,ptwo); END ProcTwo; / SUDHEER REDDY

37 POTHURAI SQL> @ d:\psr\sql\CreProc2.sql; Procedure created SQL> 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.java D:\psr\J2EE>java P2Sql SQL> select * from mytab; CONE CTWO ------------------- ---------100 200 create or replace PROCEDURE ProcThr (pa IN number,pb IN number,pc out number) as BEGIN 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 { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection ("jdbc:oracle:thin:@localhost:1521:xe","system","sunil"); SUDHEER REDDY

38 POTHURAI 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.java D:\psr\J2EE>java P3Sql res----->30 create or replace PROCEDURE ProcFour (pa IN OUT number,pb IN OUT number,pc out number) as BEGIN 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 D:\psr\J2EE>java P3Sql 110 220 330 SUDHEER REDDY

39 POTHURAI create or replace function myfunc (a number,b number) return number as BEGIN 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.java D:\psr\J2EE>java Func 300 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); System.out.println("DATE--->"+Types.DATE); System.out.println("TSTAMP--->"+Types.TIMESTAMP); } } D:\psr\J2EE>javac Constants.java SUDHEER REDDY

40 POTHURAI D:\psr\J2EE>java Constants NMERIC--->2 CHAR--->1 VARCHAR--->12 DATE--->91 TSTAMP--->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)); } } } D:\psr\J2EE>javac ConstantsApp.java D:\psr\J2EE>java ConstantsApp noc--->3 SUDHEER REDDY

41 POTHURAI CONE 1 CTWO 12 CTHR 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.java D:\psr\J2EE>java ConstantsApp1 noc--->3 CONE CHAR CTWO VARCHAR CTHR NUMERIC import java.sql.*; SUDHEER REDDY

42 POTHURAI 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-----> Oracle Oracle Database 10g Express Edition Release 10.2.0.1.0 Production true If CLADBApp is executed using the above command, it will connect to Oracle server. For connecting to MySql D:\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 { public static void main(String args[]) throws Exception { String vdrvcls,vurl,vuname,vpwd; vdrvcls=System.getProperty("drvcls"); vurl=System.getProperty("url"); SUDHEER REDDY

43 POTHURAI 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 exist D:\psr\J2EE>java -Ddrvcls=oracle.jdbc.driver.OracleDriver -Duname=system Dpwd=sunil -Durl=jdbc:oracle:thin:@localhost:1521:xe CLADDBApp ----Conneted to-----> Oracle Oracle Database 10g Express Edition Release 10.2.0.1.0 Production true SQL> desc ourtab; Name Null? Type ----------------------------------------- -------- -------------CONE NUMBER(38) CTWO FLOAT(126) CTHR NUMBER(1) CFOUR VARCHAR2(10) D:\psr\J2EE>java -Ddrvcls=com.mysql.jdbc.Driver -Durl=jdbc:mysql://localhost: 3306/test CLADDBApp

SUDHEER REDDY

44 POTHURAI 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.

olog -- connect the oracle server ologof--disconnect the server oparse--send the data oexec -- executing the data ofetch -- get the data etc
OCI API

mysql_connect mysql_close mysql_row_fetch mysql_query . etc


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 java System.out.println("----called mtwo----"); } public native void mtwo( ); static { SUDHEER REDDY

45 POTHURAI try { System.loadLibrary("ourfuncs"); } catch (Exception e) { } } } D:\psr\J2EE>javac ClsOne.java D:\psr\J2EE>javah ClsOne D:\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 __cplusplus extern "C" { #endif /* * Class: ClsOne * Method: mtwo * Signature: ( )V */ JNIEXPORT void JNICALL Java_ClsOne_mtwo (JNIEnv *, jobject); #ifdef __cplusplus } #endif #endif math.c

int add(int i,int j) { int res=i+j; return res; } int sub(int i,int j) { int res=i-j; return res; }

math.h

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


Prototype of function Implementation of function

SUDHEER REDDY

46 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.

ClsOne.java javac ClsOne.Class javah Properties of the functions ClsOne.h C/C++ code for the functions (Java_ClsOne_mtwo)
ourfuncs.c

C compiler & (+) limker m/l (machine language instructions) for the functions provided in C/C++ )
ourfuncs.dll/ourfuncs.so Windows Unix/Linux dll=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 APIS of the databases will be used (OCI in case of Oracle Driver, MySql C API in case of MySql). Type II Driver is not a pure java driver. If an application uses Type II Drivers, the following Steps must be performed.

Java classes
SUDHEER REDDY

47 POTHURAI

Code for imple in C lang


dll files

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

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 dlls 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 name Provided 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----"); } } D:\psr\J2EE>set CLASSPATH=ojdbc14.jar;. D:\psr\J2EE>javac Type2.java D:\psr\J2EE>java Type2 ---Connected---

SUDHEER REDDY

48 POTHURAI 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.java D:\psr\J2EE>java Type4 ---Connected--Type II Jar file Client S/W Type IV jar file

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 JVMS 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: 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.

SUDHEER REDDY

49 POTHURAI

.. sql Connect() { olog(.); . } .. sql disconnect() { olofoff(.); . } Compiler + linker

.. sql Connect() { Mysql_connect(.); . } .. sql disconnect() { Mysql_close(.); .. } Compiler + linker

ora.dll (ODBC Driver for Oracle)

mysql.dll (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.

Java classes C code ODBC API Native API (OCI etc)


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) 2) Install the client software. 3) Configure the client software. 4) Install the ODBC driver. 5) Configure the ODBC driver.

SUDHEER REDDY

50 POTHURAI 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.java D:\psr\J2EE>java Type1 ---Connected--Type III Driver: - It is pure java drivers.

Java App Type I/II/IV drv


DB srv

Java App
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. 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.

Type III drv

SUDHEER REDDY

51 POTHURAI 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 public class ATLight { private boolean isOn=false; public void switchOn( ) { isOn=true; SUDHEER REDDY

52 POTHURAI } 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

oos fos isOn=true t1

State of TLight obj


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( ); t1.switchOn( ); t1.displayState( ); oos.writeObject(t1); oos.close( ); } } SUDHEER REDDY

53 POTHURAI D:\psr\J2EE>javac SerApp.java D:\psr\J2EE>java SerApp ---TLight is on--D:\psr\J2EE>type test.ser sr TLighti." 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.java D:\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 xrjava.io.ObjectStream Exceptiondk9 xr java.io.IOExceptionlsde% xrjava.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. import java.io.*; public class DSerApp { public static void main(String[] args) throws Exception { SUDHEER REDDY

54 POTHURAI 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.java D:\psr\J2EE>java DSerApp ---TLight is on--java.net.Socket, java.lang.Thread, java.sql.Connection 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"); ObjectOutputStream oos=new ObjectOutputStream(fos); TLight1 t1=new TLight1( ); t1.setState( ); t1.displayState( ); oos.writeObject(t1); oos.close( ); SUDHEER REDDY etc objects are not

55 POTHURAI } } D:\psr\J2EE>javac SerApp2.java D:\psr\J2EE>java SerApp2 isOn-->true sock-->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.java D:\psr\J2EE>java DSerApp2 Exception 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)

isOn= true sock TLight1

sock

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 SUDHEER REDDY

56 POTHURAI { 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.java D:\psr\J2EE>java SerApp2 isOn-->true sock-->Socket[unconnected] notl-->10 D:\psr\J2EE>java DSerApp2 isOn-->true sock-->null notl-->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. Ex: - import java.io.*; public class TLight2 implements Serializable { private boolean isOn=true; static int notl=0; private void writeObject(ObjectOutputStream out) throws IOException { SUDHEER REDDY

57 POTHURAI 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.java D:\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"); 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. SUDHEER REDDY

58 POTHURAI D:\psr\J2EE>javac DSerApp.java D:\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 redesigned 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

empno 1 2 3

ename EOne ETwo EThr

salary 10000 20000 30000

To access the data available in the above table using hibernate, we must provide a POJO class as shown below package 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( ) { return this.empNo; } public void setEname(String ename) { this.empNo=ename; } public String getEname( ) SUDHEER REDDY

59 POTHURAI { 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.

Property type java.lang.Long java.lang.String java.lang.Double

property name empNo ename salary

org.students.Employee employee empNoempno eneme ename salary salary


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) 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) SUDHEER REDDY

60 POTHURAI 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 1 3) 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.

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

61 POTHURAI

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

9) Click on the new button in performance window. 10) Click on add jars 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.

12) Click on OK button in preferences window SUDHEER REDDY

62 POTHURAI

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

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

SUDHEER REDDY

63 POTHURAI

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

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 SUDHEER REDDY

64 POTHURAI D:\ psr J2EE HibProj1 bin src used for .class files. 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.

SUDHEER REDDY

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

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.OraSF Note: - 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 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 POTHURAI

5) In hibernate reverse engineering window a) Click on browse button & choose src folder b) 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 POTHURAI configure( )

drvcls,uname,pwd,url etc + info of hbm files


hibernate.cfg.xml

org.hibernate.cfg.configuration buildSessionFactory( )

Mapping b/w classes & tables


hbm files

org.hibernate.SessionFactory openSession( )

org.hibernate.session hibernate.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 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 oparations hsession.close( ); } } A business application performs the following 4 operations. 1) create - store the data (insert) SUDHEER REDDY

70 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 oparations Transaction 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 selected SQL> commit; Commit complete.

SUDHEER REDDY

71 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 oparations Employee 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 Application 1 EOne SUDHEER REDDY

72 POTHURAI 21 10000.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);

KOne VOne KTw o VTw o VThr

cache

Ht Entry

java.util.Hashtable

KThr

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

cach e

Hashtable kind of object


First level cache

Session hsession=sf.openSession( );

SUDHEER REDDY

73 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

cach e

Hashtable kind of object


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

cach e

Hashtable kind of object


Second level cache To be stored

1 EOne 21 10000
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 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 oparations Transaction 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.
1 EOne 21 10000

emp1

Employee hsession SL cache


2 ETwo 22 20000

emp2

Employee When 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 & its execute update statements to modify the data in employee table.

SUDHEER REDDY

75 POTHURAI HibApp3 Run As Java Application 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=? 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 oparations Transaction tx=hsession.beginTransaction( ); Employee emp1=new Employee( ); hsession.load(emp1,new Long(3)); --->1 emp1.setSalary(35000); emp1.setAge(27); hsession.evict(emp1); --->2 //hsession.update(emp1); tx.commit( ); --->3 hsession.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 POTHURAI 3---> update statement will be not being executed as the Employee object is not available in the Session cache. HibApp4 Run As Java Application 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=? Load --- attach SQL> select * from employee; Evict --- detach ENO ENAME AGE SALARY Update --- reattach ---------- --------------- ---------- ---------& attach (not load 1 EOne 25 25000 method in the 2 ETwo 26 26000 application) 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 oparations Transaction 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 Application Hibernate: select employee0_.ENO as ENO0_, employee0_.ENAME as ENAME0_0_, employee0_.AGE as AGE0_0_, employee0_.SALARY as SUDHEER REDDY

77 POTHURAI SALARY0_0_ from SYSTEM.EMPLOYEE employee0_ employee0_.ENO=? Hibernate: update SYSTEM.EMPLOYEE set ENAME=?, 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 vars (primitive data types) to null Long 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. where AGE=?,

SUDHEER REDDY

78 POTHURAI

Emp no Emp name Age Salary Store

Emp name Age Salary Store


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 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 oparations Transaction 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); --- > 1 hsession.save(emp2); --- > 2 tx.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 POTHURAI HibApp6 Run As Java Application SQL> 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

Eno ename 1 EOne 2 ETwo


Eaddrs (design one)

age 21 22 addrno 1 2 1 2 3

salary 10000 20000 street xx aa xxx aaa mmm city yy bb yyy bbb nnn state zz zz zzz zzz zzz

Primary key

Eno 1 1 2 2 2

Note: - Hibernate manuals recommends that we must avoid the tables with multiple columns in primary key. Primary key Eaddrs (design two)

eaddrid 1 2 3 4 5

Eno 1 1 2 2 2

addrno 1 2 1 2 3

street xx aa xxx aaa mmm

city yy bb yyy bbb nnn

state zz zz zzz zzz zzz

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; Name Null? Type SUDHEER REDDY

81 POTHURAI ----------------------------------------- -------- ---------------------------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.

id Eaddrsid street String city String state String

eno Long addrno Long


Eaddrsid

Eaddrs Note: - 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 oparations Transaction 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( ); pk3.setEno(new Long(1)); SUDHEER REDDY

PRIMARY KEY Class

82 POTHURAI 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 Application pk1--->23311 pk2--->23312 pk3--->23312 false true 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.

Oracle

Our code gives HQL

MySql

Hibernate translate HQL to SQL

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

org.sunil.Employee empNo empName empAge empSalary

employee eno ename age salary

Property names

Column names

SUDHEER REDDY

83 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 name SQL: - select * from employee; HQL: - from org.sunil.Employee Name of the POJO class mapped to employee table. List object
1 EOne 21 10000

Employee obj

5 EFive 25 50000

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 50000 SQL> commit; Commit complete. SUDHEER REDDY

84 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 oparations Transaction 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 Application 1 EOne 21 10000.0 2 ETwo 22 20000.0 3 EThr 23 30000.0 4 EFour24 40000.0 5 EFive25 50000.0 SQL> insert into product values (1,'pen',100.00); 1 row created. SUDHEER REDDY

85 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 50 SQL> 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 oparations Transaction 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 Application SQL> 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 POTHURAI System.out.println(o); System.out.println(i); System.out.println(by); System.out.println(b); } } D:\psr\J2EE>javac ArrayApp.java D:\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; ENAME SALARY --------------- -------------------EOne 10000 ETwo 20000 EThr 30000 EFour 40000 EFive 50000 // Here e means Elias.

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 oparations Transaction 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 POTHURAI } tx.commit( ); hsession.close( ); } } HibApp10 Run As Java Application EOne 10000.0 21 ------3 ETwo 20000.0 22 ------3 EThr 30000.0 23 ------3 EFour 40000.0 24 ------3 EFive 50000.0 25 ------3 As 3 properties are chosen hibernate creates a single dimension object array for every row & the size of the array 3. EOne 10000 21 ESix 60000 Object [] length=3 List SQL> insert into employee values (6,'ESix',26,60000); 26 SUDHEER REDDY

Object [] length=3

Get employee details

88 POTHURAI 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

Min sal Max sal

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 oparations Transaction 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( )); System.out.println("-------"); SUDHEER REDDY

89 POTHURAI } tx.commit( ); hsession.close( ); } } Here ? ---- is called as positional parameter. HibApp11 Run As Java Application 2 ETwo 22 20000.0 ------3 EThr 23 30000.0 ------4 EFour 24 40000.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, manyto-many. The relationship between employee & empaddrs is one-to-many. The relationship between empaddrs & employee is many-to-one. As shown the figure. Employee SUDHEER REDDY

90 POTHURAI

eno(PK) 1 2
Empaddrs

ename EOne ETwo

age 21 22

salary 10000 20000

aid(PK) empno addrno 1 2 3 4 5 1 1 2 2 2 1 2 1 2 3

street SOne STwo Sx Sy Sz

city COne CTwo Cx Cy Cz

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.

1 EOne 21 10000
Set Employee

Empaddrs

Empaddrs

Property name eno ename salary age empaddrs


org.sunil.Employee

Type long String Double Long Set

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

1 1 SOne COne

1 EOne 21 10000

SUDHEER REDDY

91 POTHURAI

Empaddrs

Employee

Property name aid addrno street City employee


org.sunil.Empaddrs

Type Long Long String String Employee

Used to manage the Relationship with employee Data

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 oparations Transaction 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"); ea1.setCity("COne"); SUDHEER REDDY

92 POTHURAI 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 Application SQL> select * from employee; ENO ENAME AGE SALARY -------------- ---------- ------------------ ---------------1 EOne 21 10000 SQL> 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 Application SQL> select * from employee; ENO ENAME AGE SALARY ------------ ----------------- ------------- ------------------1 EOne 21 10000 SQL> 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 ** What is lazy fetching & immediate / eager / aggressive fetching? A) package org.sunil; SUDHEER REDDY

93 POTHURAI 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 oparations Transaction 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.0 1 EOne 21 10000.0 ----calling get City---COne ----calling get City---CTwo SUDHEER REDDY

94 POTHURAI 2 4 ETwo EFour24 22 20000.0 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 DB org.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 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

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

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 . 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

SUDHEER REDDY

96 POTHURAI servers provides various facilities like hosting the web applications, hosting the EJBS, 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 wizard Start programs bea configuration wizard.

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

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

97 POTHURAI

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>startweblogic Web logic uses 7001 as it port number by default.

Dir service

http://localhost:7001/console
SUDHEER REDDY

..

98 POTHURAI

Web container EJB container


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=weblogic java.naming.security.credentials=chennakesava java.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 D:\psr\J2EE>java JndiCli Exception in thread "main" javax.naming.NoInitialContextException: Cannot instan tiate class: weblogic.jndi.WLInitialContextFactory [Root exception is java.lang. SUDHEER REDDY

99 POTHURAI ClassNotFoundException: weblogic.jndi.WLInitialContextFactory] Caused by: java.lang.ClassNotFoundException: weblogic.jndi.WLInitialContextFactory ... 5 more C:\bea\user_projects\domains\student>setenv C:\bea\user_projects\domains\student>d: D:\>cd psr D:\psr>cd j2ee D:\psr\J2EE>set CLASSPATH=%CLASSPATH%;. D:\psr\J2EE>javac JndiCli.java D:\psr\J2EE>java JndiCli ---1---{} ---2---{java.naming.factory.initial=weblogic.jndi.WLInitialContextFactory, java. naming.provider.url=t3://localhost:7001/, java.naming.security.principal=weblogi c, 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 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 POTHURAI 3) Choose view JNDI tree.

Initial Context

mbatch non e ntw o

Sub Context

Bound objects ebatch nxx x nzzz 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 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.java D:\psr\J2EE>java CSContext1

mbatch female male

Sub Context

The above structure can be created using the code shown below import javax.naming.*; import java.util.*; import java.io.*; public class CSContext2 { public static void main(String[] args) throws Exception { SUDHEER REDDY

103 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.java D:\psr\J2EE>java CSContext2

The context created by the code shown above & can be removed the code shown below import 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.java D:\psr\J2EE>java DCSContext

SUDHEER REDDY

104 POTHURAI

We can use the bind method to store a java object in the directory server import 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.java D:\psr\J2EE>java BindMethod1

SUDHEER REDDY

105 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.java D:\psr\J2EE>java BindMethod2

To replace an existing object rebind method can be used import 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 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.java D:\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.java D:\psr\J2EE>java BindMethod4 SUDHEER REDDY

107 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.java D:\psr\J2EE>java LookUp1 class 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); Object o=ic.lookup("objone"); SUDHEER REDDY

108 POTHURAI 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.java D:\psr\J2EE>java LookUp2 class java.lang.Integer class java.lang.Long class 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 { long t1,t2; t1=System.currentTimeMillis( ); Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection SUDHEER REDDY

109 POTHURAI ("jdbc:oracle:thin:@localhost:1521:xe","system","sunil"); t2=System.currentTimeMillis( ); System.out.println(t2-t1); } } D:\psr\J2EE>javac Sql.java D:\psr\J2EE>java Sql 484 D:\psr\J2EE>java Sql 437 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, oracles Driver (thin) as Database Driver & click on continue button.

SUDHEER REDDY

110 POTHURAI

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

5) Click on Test Driver configuration button.

SUDHEER REDDY

111 POTHURAI

6) Click on create and deploy button.

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

SUDHEER REDDY

112 POTHURAI Dir Srv org/Student/orads

DB

Java App

Data Source orapool


Web logic Procedure 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.

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

113 POTHURAI

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 Context FileInputStream 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 oparations con.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. Note: - Hibernate uses a connection from the connection pool for improving the performance of the application. Hibernate picks up the connection from the SUDHEER REDDY

114 POTHURAI 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 web server ----- etc browser, internet Explorer opera, Netscape etc .

Copy the HWebServer1.java file into psr/j2ee folder. C:\bea\user_projects\domains\student>setenv D:\psr\J2EE>set CLASSPATH=%CLASSPATH%;. D:\psr\J2EE>javac HWebServer1.java D:\psr\J2EE>java HWebServer1 8000 logging to stdout root=D:\psr\J2EE timeout=5000 workers=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.1 Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shock wave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application /msword, */* Accept-Language: en-us Accept-Encoding: gzip, deflate User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) Host: localhost:8000 Connection: Keep-Alive From 127.0.0.1: GET D:\psr\J2EE\One.html-->200 HTTP protocol: 1) The client establishes the connection with the server. SUDHEER REDDY

115 POTHURAI 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

Initial request line N no of HEADER LINES Blank line REQUEST BODY (optional)
Format of IRQ

REQUEST METHOD REQUESTED URI PROTO/VER


Ex: -

GET /One.html
Format of HEADER LINE

HTTP/1.1

HEADER NAME:
Ex: -

HEADER VALUE

User-Agent:
is

Our browser 1.0


os

get the data Socket

send the data

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

SUDHEER REDDY

116 POTHURAI HTTP RESPONSE FORMAT

Initial response line N no of HEADER LINES Blank line RESPONSE BODY (optional)
Format of initial Response line

PROTO/VER
Ex: -

STATUS CODE STATUS USER

HTTP/1.1

200

OK

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 request System.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 response String sresp=new String(bresp,0,nob); System.out.println(sresp); } } D:\psr\J2EE>javac WebCli.java D:\psr\J2EE>java WebCli SUDHEER REDDY

117 POTHURAI ---Connected to server-----Sent Server-----RESPONSE--HTTP/1.0 200 OK Server: Simple java Date: Fri Sep 28 16:07:49 IST 2007 Content-length: 109 Last Modified: Wed Sep 26 13:59:57 IST 2007 Content-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.java D:\psr\J2EE>java WebCli HTTP/1.0 200 OK Server: Simple java Date: Fri Sep 28 16:14:01 IST 2007 Content-length: 109 Last Modified: Wed Sep 26 13:59:57 IST 2007 Content-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. 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).

SUDHEER REDDY

118 POTHURAI 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/xml Content-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 messages 2xx --- Success 3xx --- redirect 4xx --- Error due to client 5xx --- 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.java D:\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. TRACE request method can be used to diagnolize (check) the problems if the server.

SUDHEER REDDY

119 POTHURAI 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

Das könnte Ihnen auch gefallen