1

2

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

3 { 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

*/ System.out.t are called as reference variables. System.reference variable p (person type) can refer to student object & teacher object. o=new Cone( ). System. } } D:\psr\J2EE\javac App.toString( ).println("------Ctwo:mone------").println(s). Ex: . } } D:\psr\J2EE\javac App. A super class reference can refer (point to) a sub class object.s.java D:\psr\J2EE\java App Cone@82ba41  public class Ctwo { public void mone( ) { // System.println(o). /* String s=o.4 p.out.  public class App { public static void main(String[] args) { Object o.out. return "Sudheer".out. String s=o.println(s).println("-----Ctwo:toString( )-----").out.java D:\psr\J2EE\java App -----Ctwo:toString( )----Sudheer . } public String toString( ) { System. } }  public class App { public static void main(String[] args) { Object o. o=new Ctwo( ).toString( ).

the JVM executes the toString method available in the object class.  1 o.toSting( ).  public class Emp { private int empno. ClsOne is direct super class of ClsTwo. It is indirect subclass of Object. 3 When System.  2 System. Object o = new ClsTwo( ).  1 o. 2 When a method is invoked the JVM checks for the method in the based on which the object is created. Object class is indirect super class of ClsTwo.println(o). Object o=new ClsOne( ).toString( ).out.out. This is why the JVM executes the toString method of ClsTwo.5 java. public Emp(int empno.  3 1 ClsTwo object will be created & it will be referenced by the variable o.float salary) { . private float salary. ClsTwo is direct subclass of ClsOne.println is executed internally toString method will be executed.lang. In ClsTwo toString method is available. as the method is not available in ClsOne. 2 JVM checks for toString method in ClsOne.Object String toString( )  returns clsName@ hash code extends ClsOne toString( )  not found extends ClsTwo String toString( ) { return “Sunil”}.  2 1 ClsOne object will be created & referenced by o. private String empName.String empName. In the above example “sunil” will be displayed.

Emp c2=new Emp(2. this process is called as class loading.6 this. Class cls1=Class.002f).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. this.empno=empno.String"). c1 1 EOne 100000.20000.lang.Class is a class & the objects based on this class are used & hold the details of a class.forName("java. } -------} Emp c1=new Emp(1.Date"). cls1 Info about String class Info about Date class java.lang.Class When a class Or an interface has to be used by the JVM the . this. Class cls2=Class.forName("java.001 Emp c2 2 ETwo 200000.lang.class file will be read & the information will be loaded in to the JVM’S memory.util.empName=EmpName.  java.lang.001f).  public class Appli { public static void main(String[] args) throws Exception .Class cls2 java."ETwo".salary=salary."EOne".10000.

getPackage( )).forName("java.read( ). System. System. } } . System. 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.forName("java.String).println(vsptwo).Date").out.java D:\psr\J2EE>java Appli java.read( ). System.println(cls.in. } } D:\psr\J2EE>javac Appli.String package java. Class cls2=Class.read( ). System. java platform API specification.in. System.5  The above application always loads the same class (java.read( ).lang. } } D:\psr\J2EE> javac Appli.lang.util.String").getName( )).forName method loads a class if it was not loaded earlier & returns on object of type class.in.Date").getProperty("sptwo").  public class Application { public static void main(String[] args) throws Exception { Class cls=Class.in.lang.read( ).read( ). version 1.out. System. Class cls1=Class.getProperty("spone"). String vsptwo=System.lang.out.in.7 { System. System.java D:\psr\J2EE> java –verbose Appli Class.println(cls.util.forName("java. System.println(vspone).out.in.

to know about what the application has done & why the application has failed etc… log4j API is developed by apache (www.Socket package java. The same application loads java.util.out.net.println(cls.jar: - .util. System.getPackage( )).out.8. java platform API specification.5 log4j API: -here j=java.2.java D:\psr\J2EE>java –Dclsname=java. java platform API specification.8 D:\psr\J2EE>javac Applications.net.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. The log messages helps the end user as well as the developer of the application.Vector AApplications java.println(cls.net.log >startweblogic It is always advisable to use some sort of logging API document to generate the log messages.Socket java. D:\psr\J2EE>javac AApplications. Class cls=Class. System. } } If we can run the above application using the following command java.org) & is used as part of various products like hibernate.apache.forName(vclsname).net.5 D:\psr\J2EE>java –Dclsname= java.out.util. version 1.util.Vector package java. version 1.Socket will be loaded. log4j can be used for writing the log messages to various kinds of definitions like a file. System.Vector if we use the following command.util. struts. console etc … Ex: C:\bea\user-projects\domains\pothurai\myServer\myServer. 4=for. API=application programming interface. spring etc… log4j-1.Vector java.net.getProperty("clsname").getName( )).println(vclsname). database.Socket AApplications java.

8.fatal("--msg five -.").apache. Log4j supports the following types of log message. : .jar There are various types of messages that can be generated by an application.").*. Windows OS: set CLASSPATH= . 1) debug 2) info 3) warn 4) error 5) fatal (very serious errors).8. 2) We can specify multiple directories & jar files has part of CLASSPATH environment variable.  import org. } } Layout SimpleLayout Adapter ConsoleAppender DEBUG . public class Log { public static void main(String[] args) throws Exception { Layout layout=new SimpleLayout( ).").class file.jar Current directory Environment variable Command in dos javap org.2. JVM uses the environment variable CLASSPATH to search for . C:\xyz.error("--msg four -.2.jar Linux / UNIX OS: export set CLASSPATH= .9 It contains the classes & interfaces that are part of log4j API.debug("--msg one -.8. :/USR/home: log4j-1.2."). log4j-1.log4j. Appender appender=new ConsoleAppender(layout). logger.getRootLogger( ). logger. set CLASSPATH= . C:\xyz. . logger.addAppender(appender).--msg one – formatted messages.apache."). javac.info("--msg two -.warn("--msg three -. logger. logger.Appender Name of the interface 1) java related tools like javap. log4j-1.log4j. : . Logger logger=Logger. logger.

"Log4j1.--msg one -INFO .getRootLogger( ).apache. logger. "Log4j."). Appender appender1=new ConsoleAppender(layout).jar D:\psr\J2EE>javac Log.addAppender(appender1).apache. Appender appender2=new FileAppender (layout.").addAppender(appender2).--msg two -WARN .--msg five –  import org. logger. Appender appender1=new ConsoleAppender(layout).error("--msg four -. log4j-1. .--msg three -ERROR .").--msg two -WARN .--msg four -FATAL .java D:\psr\J2EE>java Log4j DEBUG .debug("--msg one -. Logger logger=Logger. public class Log4j { public static void main(String[] args) throws Exception { Layout layout=new SimpleLayout( ).--msg three -ERROR . logger.warn("--msg three -.--msg five –  import org.java D:\psr\J2EE>java Log DEBUG .*.2.10 Logger RootLogger D:\psr\J2EE> set CLASSPATH=. } } D:\psr\J2EE>javac Log4j."). Appender appender2=new FileAppender(layout.*. Logger logger=Logger.--msg one -INFO ..html"). logger.fatal("--msg five -. logger.log4j.log").8. logger.--msg four -FATAL .getRootLogger( ). public class Log4j1 { public static void main(String[] args) throws Exception { Layout layout=new HTMLLayout( ).info("--msg two -.log4j. logger.").

").getRootLogger( ).WARN).error("--msg four -. logger.").--msg three -ERROR . logger. Logger logger=Logger.addAppender(appender)."). logger. logger. logger.log4j. logger.fatal("--msg five -. } } D:\psr\J2EE>javac Log4j1.apache. public class Log4j2 { public static void main(String[] args) throws Exception { Layout layout=new SimpleLayout( ).debug("--msg one -.").").info("--msg two -.*.warn("--msg three -. logger.error("--msg four -.java D:\psr\J2EE>java Log4j2 WARN .debug("--msg one -. logger.")."). } } D:\psr\J2EE>javac Log4j2. logger. logger.").--msg four -- . logger.addAppender(appender2). logger."). Appender appender=new ConsoleAppender(layout).fatal("--msg five -.setLevel(Level.info("--msg two -.warn("--msg three -.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."). logger.11 logger.addAppender(appender1).

layout=org.").  public class CThr { public void mone( ) { System. } } D:\psr\J2EE>javac CThr.apache.println("---CThr created---").info("--msg two -. logger. logger.").java D:\psr\J2EE>java Log4j3 ERROR .ERROR).appender. public class Log4j3 { public static void main(String[] args) throws Exception { PropertyConfigurator. log4j properties: log4j. logger.log4j.debug("--msg one -. If we want to write error & fatal error messages then we must set the log level as shown below logger.12 FATAL .getRootLogger( ).").configure("log4j.out.apache.out.properties").rootCategory=ERROR.--msg five –  configure methods reads log4j properties file & decides about the appenders. Logger logger=Logger.warn("--msg three -. logger.log4j.--msg four -FATAL . layouts.SimpleLayout  import org. A1 log4j.--msg five –  Debug is considered to be at the lowest level & fatal is consider being at the heights level.log4j. log level.A1.println("---------CThr:mOne--------").A1=org.fatal("--msg five -.java .").error("--msg four -. } public CThr( ) { System.setLevel(Level. logger.*.appender. } } D:\psr\J2EE>javac Log4j3.").ConsoleAppender log4j.apache.

getClass( )).lang.  1 Class cls=Class.newInstance( ).out.out.Class object .13  public class CFour { public void mone( ) { System.println("---------CFour:mOne--------"). } } D:\psr\J2EE>javac CFive.java  public class AApp { public static void main(String args[]) throws Exception { String vclsname=System. Cls Info about CThr class java.out. } } 1 CThr will be returned by System.out.getProperty("clsname").getProperty(…) 2 When Class.println("---CFive created---"). 2 Object o=cls. The object contains the information about CThr class.lang. } } D:\psr\J2EE>javac CFour.Class will be returned.forName is executed CThr class will be loaded (if it was not loaded earlier) & an object of type java. 3 System.println("o-->"+o.forName(vclsname). } public CFive(int i) { System.java  public class CFive { public void mone( ) { System.println("---------CFive:mOne--------").

lang. if it is executed using the command as shown below java -dclsname=Cxxx AApp D:\psr\J2EE>javac AApp. NTBC (I mean) Prefix of interface IBillCalculator float calcBill(String cid.newInstance0(Unknown Source) at java.14 3 When newInstance( ) method executed.int nocu). it will create an object of type CThr using the zero argument constructor of CThr class.lang.  We can develop the flexible java applications by using the interfaces.class then newInstance( ) method fails to create an object. 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 } .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. o CThr object  The same application creates an objects of type Cxxx.main(AApp.Class.InstantiationException: CFive at java.java:7) 1 error Because the CFive class is contain parameter argument constructor.lang. Note: .if there is no zero argument constructor in CThr in CThr.newInstance(Unknown Source) at AApp.Class.

bc=new ATBillCalculator( ). bc=new Student( ). int utc=nocu-200.java  A reference variable of type interface can refer to an object that is based on a class that implements the interface. .getProperty("clsname"). IBillCalculator bc. Object o=cls.main(TBApp. IBillCalculator bc.int nocu) { // code to calculate bill all to airtel System.  public class Student { } D:\psr\J2EE>javac Student.java  public class TBApp { public static void main(String args[]) throws Exception { String vclsname=System. Class cls=Class.ClassCastException: Student at TBApp.newInstance( ).lang.out.println("----AIRTEL----").java D:\psr\J2EE>java –Dclsname=Student TBApp Exception in thread “main” java.java:9) 1 error  public class ATBillCalculator implements IBillCalculator { public float calcBill(String cid. X // because it is not implemented.15  public interface IBillCalculator { float calcBill(String cid. } } D:\psr\J2EE>javac TBApp.forName(vclsname).int nocu). float billAmt=100. } D:\psr\J2EE>javac IBillCalculator. bc=(IBillCalculator)o.

forName(vclsname). float ba=bc. Class cls=Class. D:\psr\J2EE>javac ATBillCalculator.println("------tc successful------"). D:\psr\J2EE>java –Dclsname= ATBillCalculator TBApp ------tc successful---------AIRTEL---Bill Amount-->300.  The above application is very flexible. o bc ATBillCalculator object 3 When calcBill is called the JVM executes the calcBill method of ATBillCalculator.calcBill("xyz".out.println("Bill Amount-->"+ba).400). 2 Type casting will be performed & ATBillCalculator object will be referred by the variable bc.out. Object o=cls.newInstance( ). We can make this application work for HUTCH without disturbing the existing code. } return billAmt.java 1 An object of type ATBillCalculator will be created & it will be referred by the variable o. } } The code in the method calcBill is implemented according to the policies.  2 System.  3 System.0  public class HBillCalculator implements IBillCalculator . 1 IBillCalculator bc.16 if(utc>0) { billAmt+=(utc*1). } } D:\psr\J2EE>javac TBApp.java  public class TBApp { public static void main(String args[]) throws Exception { String vclsname=System. bc=(IBillCalculator)o.getProperty("clsname").

return billAmt. int utc=nocu-225. if(utc>0) { billAmt+=(utc*1.int nocu) { // code to caluclate bill all to NTBC System. . float billAmt=100.java D:\psr\J2EE>java –Dclsname=NTBC TBApp ------tc successful--------.75 The above application exhibits multiple behaviors (polymorphic).  public class NTBC implements IBillCalculator { public float calcBill(String cid.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--------.17 { public float calcBill(String cid. } } D:\psr\J2EE>javac NTBC.int nocu) { // code to caluclate bill all to airtel System. } return billAmt. float billAmt=0.out.println("----NT----"). } } D:\psr\J2EE>javac HBillCalculator.out.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.25).HUTCH ---Bill Amount-->318.println("----HUTCH----").NT ---Bill Amount-->300. It works where any class provides the implementation of IBillCalculator interface.75. billAmt+=nocu * 0.

EJB. (www.  JEE is a combination of API’S like java mail API. ip—196.12.  For a java developer an API is a set of classes & interface.sql.etc… A java application must establish the connection with the database to use /talk with the database server. J2sdk: .Used to send & receive mails from a java application. public class Jdbc { public static void main(String[] args) throws Exception { . but we can not create an object based on interface. jndi. Micro Soft SQL server. any number of classes can be provided implementing the same interface & these classes can be provided by any company.1 port—1521 service name—xe Oracle server Connection object Java App Ojdbc14 provided by Oracle Corporation. IBillCalculator bc=new IBillCalculator( ). Java Mail API: . 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. AWT/WING. MySql server. networking API etc… are part of java standard edition. Java TAPI: . DB2 --.100.  Java soft has designed various API’S.*. JMS etc… JDBC API is a part of java standard edition.  The technique shown in TBApp is used heavily in the design of several API’S. SyBase.(Java Database connectivity) -.Used to deal with database servers. IBillCalculator bc.Java Telephonic application programming interface. JDBC API: .com) This files contains is a set of classes that are implemented by Oracle corporation. We can use JDBC to access the databases like Oracle. that the design for a specific purpose.Java software development kit.18 1) We can declare a reference variable of type interface.oracle. products / projects. X 2) Once an interface is provided by a company. servlet API. A set of API’S like jdbc. Ingress.  import java.

java:7: cannot find symbol symbol : class oracleDriver location: class Jdbc con=new oracleDriver( ).jar.oracleDriver provided by Oracle . } } D:\psr\J2EE>javac Jdbc.Connetion provided by Oracle oracle.jdbc.sql.jdbc.internal.oracleDriver provided by Oracle java.driver.19 Connection con. ^ 1 error D:\psr\J2EE> set CLASSPATH=ojdbc14.println(“------Connected------”).. con=new oracleDriver( ).java D:\psr\J2EE>java Jdbc Jdbc.sql.driver.jdbc.jdbc.out. D:\psr\J2EE>java Jdbc -----Connected------ java. System.oracleConnetion provided by Oracle oracle.Connection provide java soft oracle.Driver provide java soft oracle.

Connected -->class oracle. Ex: . JDBC Driver: . mysql-Connector-java-3.registerDriver(drv). System.0. by java soft In order to establish the connection the name of the driver class & the format of JDBC URL is required."system".T4CConnection  import java.*. Statement.*."sunil").11-stable.mysql. public class MyApp { public static void main(String[] args) throws Exception { . java soft has provided several interfaces like java.sql.sql. For this information we can refer to the manual / documentation provided by the Vendor of the JDBC driver.sql.mysql.20 As part of JDBC API.jar. mysql-Connector-java-3.Connected -->"+con. preparedStatement etc … Driver class: . public class OraApp { public static void main(String[] args) throws Exception { Driver drv=new oracle.bin.sql.Driver --. CalledStatement.ojdbc14.11-stable.sql.com) It provided by MySql AB.Driver is a Driver class provided by MySql AB mysql-Connector-java-3.driver.out.A class that provides the implementation of java.  import java.getClass( )).tar.driver. that or are part of JDBC API. ResultSet. Connection con=DriverManager. java. DriverManager.jdbc.0.jar contains the classes that implements JDBC related interfaces.jar.jdbc.getConnection ("jdbc:oracle:thin:@localhost:1521:xe".java D:\psr\J2EE>java OraApp --.com.Statement Interfaces provided Classes implementing the interface of JDBC API provided by oracle corp.11-stable.println("--.it is a set of classes provides the implementation of the interfaces.0. Connection.OracleDriver( ).jdbc. } } D:\psr\J2EE>javac OraApp.Driver interface.bin.Connection --.Driver.gz-----(www. Ex: .

driver.println("------XDrv executed------"). Ex: .getConnection ("jdbc:mysql://localhost:3306/test".driver.getClass( )).registerDriver(drv). DriverManager. System. DriverManager. } } * How to register a Driver?:  1) We can register the driver using DriverManager.out. } } D:\psr\J2EE>javac XDrv.forName("XDrv").registerDriver(drv)." ").println("--. As a part of static block of a driver class code will be provided for registering the driver.jdbc. DriverManager.jdbc.out. Ex: . Connection con=DriverManager.OracleDriver( ). Ex: public class XDrv { static { System.Driver( ).OracleDriver( ).Driver drv=new oracle.public class OracleDriver -----{ Static { Driver drv=new oracle.registerDriver.registerDriver(drv).  2) When a class is loaded the static block available in the class will be executed by the JVM.21 Driver drv=new com.Connected -->"+con. } } 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.mysql.jdbc. } } .java  public class Xdrv1 { public static void main(String[] args) throws Exception { Class." ".

java D:\psr\J2EE>java DBApp SQL> desc employee. Connection con=DriverManager.oracle.Connection interface.*.salary number(10. stmt.-------.driver.executeUpdate(vsql). 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.Connection interface (ex: . } } D:\psr\J2EE>javac DBApp.forName("oracle. internally it will call the connect method available in the Driver class provide by the driver vendor. The code of the static block of the driver class registers the driver.jdbc.2))".  2) When the application class DriverManager.forName("oracle.sql. public class DBApp { public static void main(String args[]) throws Exception { Class."system".OracleConnection .driver.2) .sql.22  4) When forName is executed the driver class will be loaded. com.Connection are the classes that implements connection interface).jdbc.Class. Name Null? Type ----------------------------------------.driver."sunil"). String vsql="create table employee (empname varchar(10).getConnection. Statement stmt=con. Ex: . empno number(3).createStatement( ). Create ….OracleDriver")..---------------------------EMPNAME VARCHAR2(10) EMPNO NUMBER(3) SALARY NUMBER(10.getConnection ("jdbc:oracle:thin:@localhost:1521:xe". * How can your application create a connection object?:  1) Every jdbc driver vendor provides a class implementing java.mysql. Connection Statement Oracle server Java DBApp (client)  import java.OracleDriver ").jdbc.sql. by JVM executes the static class of the driver class.

2. …. SQL> select * from employee.3.*.OracleDriver").executeUpdate is called repeatedly (200 times). Commit complete. 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.executeUpdate(vsql). Empname: Empno: Salary: EOne 1 10000 Store emp insert into employee values (‘EOne’.forName("oracle. 2) The database server splits the SQL statement into multiple pieces to analyze whether the statement is valid or not.10000) insert into employee values (‘ETwo.  import java.SqlException. no rows selected SQL> commit.sql. 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.jdbc.20000) …. the jdbc driver sends the sql statements for 200 times to the server.sql. insert into employee values (‘Exyz’.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.1.23  When stmt.driver. . public class SDBApp { public static void main(String args[]) throws Exception { Class. When stmt. b) if the statement is valid the server executes the statement (the server carries out the appropriate task requested by the SQL statement). The server performs parsing for 200 times & carries out the execution for 200 times.

--------------------. // code to connect to DB String vsql="insert into employee values(?. pstmt.forName("oracle.---------.jdbc.?)". // code to connect to DB Statement stmt=con. stmt. String vsql200="insert into employee values (200. .createStatement( ). stmt. EMPNAME EMPNO SALARY ---------. PreparedStatement pstmt=con.'EOne'. para1. prepareStatement(vsql).sql. ? .driver. } } D:\psr\J2EE>javac SDBApp.11111)"."EOne"). We can improve the performance of these kinds of applications using PreparedStatement object instead of a statement object.?. para2. para3  import java. Parameters Place holders bind variables insert into employee values ( ? ."sunil").------------EOne 1 10000 ETwo 2 20000 EXyz 200 11111 The above application is repeatedly executing the “same statement with a different set of values”.20000)". These question marks are called as parameters / place holders / bind variables.getConnection ("jdbc:oracle:thin:@localhost:1521:xe".'ETwo'. Connection con=DriverManager."system".*.setString(1.24 Connection con=DriverManager.java D:\psr\J2EE>java SDBApp SQL> select * from employee.10000)".executeUpdate(vsql1). ? ).executeUpdate(vsql2).executeUpdate(vsql200)."system". stmt.OracleDriver"). String vsql1="insert into employee values (1."sunil").'EXyz'.getConnection ("jdbc:oracle:thin:@localhost:1521:xe". As a part of SQL statements we must use the question mark (?) as shown below without providing the values. public class PSDBApp { public static void main(String args[]) throws Exception { Class. String vsql2="insert into employee values (2.

In this case parsing is carried out only once."EXyz"). ."sunil"). the performance of application will be improved. } } D:\psr\J2EE>javac PSDBApp. The server parses the statement & the driver provides the values to the server.OracleDriver"). EMPNAME EMPNO SALARY ---------. public class DDBApp { public static void main(String args[]) throws Exception { Class.11111).forName("oracle.setInt(2. // code to connect to DB String vsql="delete from employee where empno=?".1).executeUpdate( ). PreparedStatement pstmt=con. pstmt. pstmt.driver.jdbc. pstmt. pstmt.200).executeUpdate( ).1).10000). By reducing the number of parses. pstmt.executeUpdate( ). pstmt.------------EOne 1 10000 ETwo 2 20000 EXyz 200 11111 The JDBC driver sends the SQL statement to the server.setFloat(3.*.  import java.setString(1. pstmt.setFloat(3."ETwo"). pstmt.executeUpdate( ). pstmt.25 pstmt.setInt(1.---------.sql.setInt(2. pstmt.java D:\psr\J2EE>java PSDBApp SQL> select * from employee. The server executes the statement using the values. The server executes the statement which was parsed earlier using the values provided by the driver."system".setInt(1.2). The driver provides the values of the parameters to the server. where as in case of the statement objects parsing is carried out from 200 times.setFloat(3. pstmt. pstmt. pstmt.getConnection ("jdbc:oracle:thin:@localhost:1521:xe".setInt(2. Connection con=DriverManager.executeUpdate( ).20000).setString(1.prepareStatement(vsql).--------------------. pstmt.2).

sql.2).---------. . SQL> select * from employee. Update employee set salary=40000 where empno=1.2."60000").forName("oracle. 1 row created.executeUpdate( ). pstmt."sunil"). SQL> insert into employee values ('EXyz'."50000"). Update employee set salary=50000 where empno=2."40000").jdbc. pstmt.getConnection ("jdbc:oracle:thin:@localhost:1521:xe".10000).1.setString(1.*. pstmt. } } D:\psr\J2EE>javac DDBApp.26 pstmt.prepareStatement(vsql). Commit complete."2"). PreparedStatement pstmt=con.OracleDriver"). pstmt. pstmt.setString(1.java D:\psr\J2EE>java DDBApp SQL> select * from employee. pstmt."system".executeUpdate( ). SQL> insert into employee values ('ETwo'. 1 row created.200.  import java."200").setString(1.driver.setString(2. pstmt. // code to connect to DB String vsql="update employee set salary=? where empno=?".200).setString(2. EMPNAME EMPNO SALARY ---------. public class StDBApp { public static void main(String args[]) throws Exception { Class. SQL> insert into employee values ('EOne'. no rows selected We can use PreparedStatement to execute the Update statement. pstmt.----------------.executeUpdate( ). Update employee set salary=60000 where empno=200.1). Connection con=DriverManager.-------------ETwo 2 2 EXyz 200 10000 EOne 1 1 SQL> commit.setInt(1. select statement also. 1 row created.

-----------------ETwo 2 50000 EXyz 200 60000 EOne 1 40000 * What is the difference between executeUpdate & executeQuery? : executeQuery is for executing a select statement. Statement stmt=con.OracleDriver").executeUpdate( ).27 pstmt.println("------nore----->"+nore).out. int nore=stmt. String vsql="delete from employee".forName("oracle.executeUpdate(vsql)."sunil").jdbc. } } D:\psr\J2EE>javac DeDBApp.createStatement( ).---------.driver. Connection con=DriverManager. 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.getConnection ("jdbc:oracle:thin:@localhost:1521:xe". public class DeDBApp { public static void main(String args[]) throws Exception { Class. The return type of executeUpdate indicates the number of rows affected.java D:\psr\J2EE>java DeDBApp ------nore----->3 SQL> select * from employee. executeUpdate returns 0. } } D:\psr\J2EE>javac StDBApp.java D:\psr\J2EE>java StDBApp SQL> select * from employee.  delete from employee Ex:import java. System."1").sql.setString(2. executeUpdate method is for executing non select statement & the return type of executeUpdate is int. .*. the return type of executeQuery method is ResultSet."system"..----------. EMPNAME EMPNO SALARY ---------. pstmt. but it be use “drop table employee”.

getRow( )).createStatement( ).getConnection ("jdbc:oracle:thin:@localhost:1521:xe". Connection con=DriverManager.out.executeUpdate(vsql). rs.-----------------1 EOne 10000 2 ETwo 20000 3 EThr 30000  import java.OracleDriver").---------.OracleDriver").forName("oracle."sunil").getRow( )).java D:\psr\J2EE>java DeDBApp ------nore----->0 SQL> select * from employee."sunil").out.*. String vsql="select * from employee".driver. System.sql. } } D:\psr\J2EE>javac DeDBApp.println("--cur row -->"+rs. Statement stmt=con.out.next( ).driver.jdbc. ResultSet rs=stmt. Connection con=DriverManager. public class RSDBApp { public static void main(String args[]) throws Exception { Class.next( )."system".sql.println(rs.println("------nore----->"+nore). public class DeDBApp { public static void main(String args[]) throws Exception { Class.getRow( )).createStatement( ).println(rs.out.jdbc. System. select * from employee * ERROR at line 1: ORA-00942: table or view does not exist SQL> select * from employee. String vsql=" drop table employee”.*. System.---------. .getConnection ("jdbc:oracle:thin:@localhost:1521:xe".executeQuery(vsql).28  import java. rs. EMPNO ENAME SALARY ---------. Statement stmt=con. int nore=stmt."system".forName("oracle. System.

String vsql="select * from employee". Connection con=DriverManager.getRow( )).println(rs.println(rs.out.next( ). .getConnection ("jdbc:oracle:thin:@localhost:1521:xe". rs. System.println("--cur row -->”+rs.OracleDriver").getFloat("salary")). ResultSet rs=stmt."sunil").println(rs.getRow( )).getRow( )).println(rs.29 rs.getInt("empno")). When the ResultSet is opened.next( ).forName("oracle.*.driver.out. This method returns false. public class RSDBApp { public static void main(String args[]) throws Exception { Class. when it points to after last row.out.executeQuery(vsql).println(rs.next( ).next( )) { System. while(rs. rs.out. System.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.out. } } D:\psr\J2EE>javac RSDBApp.createStatement( ).getString("ename")). System. ResultSet Java DBApp Database  import java."system". it will be pointing to before first row.jdbc.next( )moves the Resultset current row pointer to the next available row. Statement stmt=con.sql.out. System. System. rs. Employee empno….

"sunil"). rs.sql. it will get the modified data). We can use next. String vsql="select empno. 2) Scroll InSensitive ResultSet: ."system".ResultSet. .forName("oracle.read( ). absolute methods on scrollable ResultSet.OracleDriver").CONCUR_READ_ONLY).0 --cur row -->3 3 EThr 30000.getInt("empno")). System.0 --cur row -->2 2 ETwo 20000. ResultSet rs=stmt.println("--about read 3rd row--").).salary from employee".out.  import java.We can use the method refreshRow( ) & get the fresh data (if the data is modified. 1) Scroll Sensitive ResultSet: . System.out.read( ).driver.30 System.ename.read( ).jdbc. first. public class RSSDBApp { public static void main(String args[]) throws Exception { Class.absolute(3).in.*. System.executeQuery(vsql). Connection con=DriverManager. Statement stmt=con. last. } } } D:\psr\J2EE>javac RSDBApp. We can not use the methods previous.The ResultSet is not sensitive to the changes made by another client.println(rs. first.in. That is we can not get the fresh data using refreshRow( ) method.getConnection ("jdbc:oracle:thin:@localhost:1521:xe".TYPE_ SCORLL_SENSITIVE.0 By default read only. System. rs. There are 2 types of scrollable ResultSets. last & absolute on forward only ResultSet.createStatement(ResultSet. Forward only ResultSet allows next method (that is we can move only in the forward direction.java D:\psr\J2EE>java RSDBApp --cur row -->1 1 EOne 10000.read( ).in. previous.in. forward only ResultSet will be created. System. Scrollable ResultSet allows an application to move in both the directions.refreshRow( ).

0 We can not insert.salary from employee".out.absolute(3).updateRow( ). } } D:\psr\J2EE>javac RSUDBApp.OracleDriver").println(rs. } } D:\psr\J2EE>javac RSSDBApp.out. rs. ResultSet rs=stmt.jdbc.executeQuery(vsql).updateXxx( )method is used.*. rs. System.createStatement(ResultSet.31 System. rs."system".---------.  import java. rs.ename.getFloat("salary")).getString("ename")). update and delete the data using READ_ONLY ResultSet (only read operation is permitted on read only ResultSet).updateRow( ) must be used.updateString("ename".TYPE_ SCORLL_SENSITIVE."sunil"). .java D:\psr\J2EE>java RSUDBApp SQL> select * from employee2.driver. the data will be modified in the ResultSet. Statement stmt=con."45000").getConnection ("jdbc:oracle:thin:@localhost:1521:xe". EMPNO ENAME SALARY ---------.ResultSet.java D:\psr\J2EE>java RSSDBApp --about read 3rd row-3 EThr 30000. String vsql="select empno. To delete the fourth row we can use the code as shown below.CONCUR_UPDATABLE).---------."NEThr").updateString("salary".println(rs.----------------1 EOne 10000 2 ETwo 20000 3 NEThr 45000 When rs. Connection con=DriverManager. To apply these changes to the database rs.sql. public class RSUDBApp { public static void main(String args[]) throws Exception { Class.forName("oracle.

updateRow( ).-------------------1 EOne 10000 3 Sunil 25000 To insert the row we can use the code as shown below."12345"). Statement stmt=con. String vsql="select empno.ResultSet.updateString("ename".executeQuery(vsql)."system". public class RSDDBApp { public static void main(String args[]) throws Exception { Class. rs. } } D:\psr\J2EE>javac RSDDBApp. rs.absolute(3).forName("oracle.getConnection ("jdbc:oracle:thin:@localhost:1521:xe". public class RSIDBApp { public static void main(String args[]) throws Exception { Class. rs.updateString("empno".salary from employee"."NewEmp").ename. EMPNO ENAME SALARY ---------.*. Statement stmt=con.CONCUR_UPDATABLE).---------. ResultSet rs=stmt. Connection con=DriverManager."system".---------.OracleDriver"). ResultSet rs=stmt. rs.absolute(2). rs.  import java.createStatement(ResultSet.updateString("salary".jdbc.salary from employee". rs."25000").sql.32  import java.driver.createStatement(ResultSet.ename.java D:\psr\J2EE>java RSDDBApp SQL> select * from employee2. Connection con=DriverManager. String vsql="select empno.getConnection ("jdbc:oracle:thin:@localhost:1521:xe". . rs. rs."sunil").TYPE_ SCORLL_SENSITIVE.CONCUR_UPDATABLE)."Sunil").driver."sunil").sql.ResultSet.updateString("ename". rs.executeQuery(vsql).deleteRow( ).forName("oracle.TYPE_ SCORLL_SENSITIVE."100").updateString("salary". rs.*.jdbc.moveToInsertRow( ).OracleDriver").

---------.‘Sunil’. EMPNO ENAME SALARY ---------.‘stwo’).-------------------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.---------.‘cone’.‘sone’).12345). insert into empaddrs values (100.33 rs. insert into empaddrs values (100.java D:\psr\J2EE>java RSIDBApp SQL> select * from employee2. . } } D:\psr\J2EE>javac RSIDBApp.‘Stone’.‘Sttwo’.insertRow( ).‘ctwo’.

OracleDriver").forName("oracle. the JDBC driver will not commit a transaction after executing the SQL statement. In auto commit mode. city varchar(10). String vsql1="insert into employee values (100.getConnection ("jdbc:oracle:thin:@localhost:1521:xe". 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. 2) When the current transaction is ended.In majority of classes a business application must execute multiple SQL statements as part of a transaction. Table created.setAutoCommit(false).rollback( )  to roll back the transaction.'stwo')". Statement stmt=con. the JDBC driver commits a transaction after executing every sql statements. When auto commit is set to false."sunil").'ctwo'. SQL> create table employee (eno number(4) primary key.'sone')".12345)". In the above application the following 3 statements must be executed as part of the transaction. If an application has to control the transaction then the auto commit must be set to false.'stone'.ename varchar(10). state varchar(10)). the transaction is started.'cone'. Committing or rolling back a transaction ends transaction. no rows selected  import java. con. SQL> create table empaddrs (eno number(4). the application has to do some work (person transaction). 3) A new transaction will be started. Connection con=DriverManager.createStatement( ). Table created. no rows selected SQL> select * from empaddrs. public class TDBApp { public static void main(String args[]) throws Exception { Class.commit( )  to commit the transaction."system".2)). By default the JDBC driver uses “auto commit mode”. In this case the application is responsible for using con. .'sttwo'.sql.jdbc. SQL> select * from employee. String vsql2="insert into empaddrs values (100.driver. A new transaction will be started in one of the following cases 1) When a connection is establish.*. con.'Sunil'.salary number(10.34 When the user (shown above) feeds the data & clicks on the store button. Note: . street varchar(10). String vsql3="insert into empaddrs values(100.

ENO STREET CITY STATE ---------.executeUpdate(vsql2). public class TADBApp { public static void main(String args[]) throws Exception { Class. stmt.executeUpdate(vsql1). System.executeUpdate(vsql3). .sql. con.'ctwo'.'sone') --executed-->insert into empaddrs values(100. } catch (Exception e) { con.in. Connection con=DriverManager. System.'sttwo'. System.read( ).println("--executed-->"+vsql3).OracleDriver").read( ). A group of statements is called as a batch of statements. System.getConnection ("jdbc:oracle:thin:@localhost:1521:xe".println("--executed-->"+vsql1).in. System.---------. System.setAutoCommit(false).  import java.'Sunil'.out.java D:\psr\J2EE>java TDBApp --executed-->insert into employee values(100.12345) --executed-->insert into empaddrs values(100. stmt.---------. System.----------------100 Sunil 12345 SQL> select * from empaddrs.in.---------. try { stmt.read( ).'cone'. System.driver.read( ).jdbc.---------.---------.35 con.out.-----------100 stone cone sone 100 sttwo ctwo stwo  Batch updates improves the performance of the applications.commit( ).in.rollback( )."system".read( ).out.in. ENO ENAME SALARY ---------."sunil"). } } } D:\psr\J2EE>javac TDBApp. System.'stone'.forName("oracle.in.*.println("--executed-->"+vsql2).read( ).'stwo') SQL> select * from employee.

con.---------.addBatch(vsql3).setAutoCommit(false).'sone')". stmt.clearBatch( ).12346)".addBatch(vsql1).'sttwo'.36 Statement stmt=con.'Sudheer'.commit( ). ENO ENAME SALARY ---------. Data base name tot inc name 1.50.. try { stmt. stmt. String vsql3="insert into empaddrs values(101. stmt.---------. } catch (Exception e) { con.'stwo')".rollback( ).'ctwo'.java D:\psr\J2EE>java TADBApp SQL> select * from employee.---------.addBatch(vsql2).---------.-----------100 Sunil 12345 101 Sudheer 12346 SQL> select * from empaddrs.----------------100 stone cone sone 100 sttwo ctwo stwo 101 stone cone sone 101 sttwo ctwo stwo tax rates min max tr spcalcx ……. ENO STREET CITY STATE ---------. stmt. String vsql1="insert into employee values(101.createStatement( ).000 Clac tax Java App .executeBatch( ). String vsql2="insert into empaddrs values(101.'cone'. con.---------.'stone'. } } } D:\psr\J2EE>javac TADBApp.

sql. CTwo number). cstmt. } } D:\psr\J2EE>javac P1Sql.java D:\psr\J2EE>java P1Sql SQL> select * from mytab."sunil").driver. Sp’s improves the performance of the application & are used for the implementation to call a stored procedure. insert into mytab values (100. We can use CallableStatement to call a stored procedure. Table created. / SQL> @ d:\psr\sql\CreProc1.forName("oracle.---------100 55  create or replace PROCEDURE ProcTwo . Procedure created SQL> create table mytab (COne number .-------CONE NUMBER CTWO NUMBER SQL> select * from mytab. CONE CTWO ------------------.37 Most of the database servers support the stored procedures.sql.getConnection ("jdbc:oracle:thin:@localhost:1521:xe". public class P1Sql { public static void main(String args[]) throws Exception { Class."system". BEGIN data type i:=44+11. END ProcOne. SQL> desc mytab. no rows selected We can use the code shown below to invoke proc1 import java. Name Null? Type ----------------------------------------.prepareCall("{call ProcOne}").-------.jdbc. CallableStatement cstmt=con.OracleDriver").  create or replace PROCEDURE ProcOne as i number. Connection con=DriverManager.execute( ).*.i).

"sunil"). no rows selected  import java. END ProcTwo. CONE CTWO ------------------.java D:\psr\J2EE>java P2Sql SQL> select * from mytab. cstmt. Connection con=DriverManager.*. public class P3Sql { .ptwo). public class P2Sql { public static void main(String args[]) throws Exception { Class. cstmt.setInt(2.ptwo IN number) as BEGIN insert into mytab values (pone.getConnection ("jdbc:oracle:thin:@localhost:1521:xe".jdbc.sql.*.sql. / SQL> @ d:\psr\sql\CreProc3. END ProcThr.100). 1 row deleted. SQL> select * from mytab.forName("oracle.execute( ). Procedure created  import java. cstmt.pb IN number.pc out number) as BEGIN pc:=pa+pb.38 (pone IN number."system". Procedure created SQL> delete mytab.setInt(1. } } D:\psr\J2EE>javac P2Sql.?)}").---------100 200  create or replace PROCEDURE ProcThr (pa IN number. / SQL> @ d:\psr\sql\CreProc2. CallableStatement cstmt=con.sql.OracleDriver").prepareCall("{call ProcTwo(?.driver.sql.200).

39 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 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)); } }

40 D:\psr\J2EE>javac P3Sql.java D:\psr\J2EE>java P3Sql 110 220 330  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);

41 System.out.println("VARCHAR--->"+Types.VARCHAR); System.out.println("DATE--->"+Types.DATE); System.out.println("TSTAMP--->"+Types.TIMESTAMP); } } D:\psr\J2EE>javac Constants.java 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)); }

CHAR: System.out. String vsql="select * from test".executeQuery(vsql).createStatement( ). System.i++) { System.NUMERIC: System.println("NUMERIC")."sunil"). ResultSet rs=stmt.OracleDriver").jdbc.VARCHAR: System.i<=noc.println("Unknown"). switch(rsmd.getConnection ("jdbc:oracle:thin:@localhost:1521:xe".42 } } D:\psr\J2EE>javac ConstantsApp.java D:\psr\J2EE>java ConstantsApp noc--->3 CONE 1 CTWO 12 CTHR 2  import java.println("noc--->"+noc).java D:\psr\J2EE>java ConstantsApp1 . case Types. int noc=rsmd.getColumnType(i)) { case Types.println("VARCHAR").forName("oracle.getMetaData( ). default: System.getColumnName(i)+"\t").*. ResultSetMetaData rsmd=rs.sql.out.out. break.getColumnCount( ).out. case Types. Connection con=DriverManager. break. } } } } D:\psr\J2EE>javac ConstantsApp1. for(int i=1. break.out. public class ConstantsApp1 { public static void main(String args[]) throws Exception { Class.println("CHAR").out. Statement stmt=con."system".driver.print(rsmd.

jdbc.getDatabaseProductVersion( )). System.mysql.sql. For connecting to MySql D:\psr\J2EE>java -Ddrvcls=com.getProperty("pwd").out. Connection con=DriverManager.println("----Conneted to----->").getDatabaseProductName( )). } } The above application will be able to establish the connection with any kind of database.println(dbmd. DatabaseMetaData dbmd=con. vdrvcls=System. vurl=System.0 Production true If CLADBApp is executed using the above command.out.out.getProperty("uname").Driver -Durl=jdbc:mysql://localhost: 3306/test CLADBApp ----Conneted to-----> MySql Note: . vpwd=System.Even though SQL is a standard language different database servers supports slightly different grammar for SQL. System.sql.OracleDriver -Duname=system –Dpwd=sunil -Durl=jdbc:oracle:thin:@localhost:1521:xe CLADBApp ----Conneted to-----> Oracle Oracle Database 10g Express Edition Release 10.vurl. it will connect to Oracle server.2.out.43 noc--->3 CONE CHAR CTWO VARCHAR CTHR NUMERIC  import java.getConnection (vurl.println(dbmd.getProperty("drvcls"). System.driver. vuname=System.1. public class CLADDBApp .vuname.vpwd).supportsStoredProcedures( )).vpwd. D:\psr\J2EE>java -Ddrvcls=oracle.*. System.println(dbmd.getProperty("url").  import java.vuname.getMetaData( ).0.forName(vdrvcls).jdbc. public class CLADBApp { public static void main(String args[]) throws Exception { String vdrvcls.*. Class.

getDatabaseProductVersion( )).supportsStoredProcedures( )). vurl=System.getConnection (vurl.createStatement( ). System.vpwd.out.getDatabaseProductName( )). String vsql=null. CTwo float.driver.vuname.out.executeUpdate(vsql). vdrvcls=System. stmt. } } SQL> desc ourtab. System.vuname.out.println(dbmd. } if(dbname. CThr number(1).println(dbmd. } Statement stmt=con.getProperty("drvcls"). CTwo float. DatabaseMetaData dbmd=con.-------.out.getProperty("uname"). String dbname=dbmd.2. ERROR: ORA-04043: object ourtab does not exist D:\psr\J2EE>java -Ddrvcls=oracle. if(dbname. Name Null? Type ----------------------------------------.jdbc.getProperty("url"). CFour varchar(10))".println("----Conneted to----->"). CFour varchar(10))". CThr bit.forName(vdrvcls). Class.getMetaData( ). Connection con=DriverManager.OracleDriver -Duname=system –Dpwd=sunil -Durl=jdbc:oracle:thin:@localhost:1521:xe CLADDBApp ----Conneted to-----> Oracle Oracle Database 10g Express Edition Release 10.vpwd). vuname=System.getDatabaseProductName( ).vurl.0.0 Production true SQL> desc ourtab.println(dbmd.44 { public static void main(String args[]) throws Exception { String vdrvcls.1. System.equals("Oracle")) { vsql="create table ourtab (COne integer.getProperty("pwd"). vpwd=System. System.equals("MySql")) { vsql="create table ourtab (COne integer.-------------CONE NUMBER(38) CTWO FLOAT(126) .

println("----Calling mtwo----"). to deal with MySql server. // (some) code in java . mtwo( ).jdbc. Type-II. olog -. There are 4 types of JDBC drivers (Type-I.connect the oracle server ologof--disconnect the server oparse--send the data oexec -. Type-III & Type-IV) DB Native API: .Driver -Durl=jdbc:mysql://localhost: 3306/test CLADDBApp 1) We can use the products like JDO (java data object). Like OCI. to access the databases. API deal with oracle. 2) These products internally use JDBC API.45 CTHR CFOUR NUMBER(1) VARCHAR2(10) D:\psr\J2EE>java -Ddrvcls=com. Hibernate etc…. 3) As a developer we need not worry about the differences between the databases when use the above products. MySql C API a native API is provided for most of the databases. JNI (java native interface): public class ClsOne { public void mone( ) { System. etc MySql C API A ‘C’ program can use oracle call interface (OCI).out.mysql.executing the data ofetch -. TOPLINK. MySql C API is called as native API of MySql server. A ‘C’ program can use MySql C API. OCI is called as native API of Oracle.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.get the data … etc OCI API mysql_connect mysql_close mysql_row_fetch mysql_query ….

static { try { System.println("----called mtwo----").h int add(int. #ifdef __cplusplus } #endif #endif math.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 *. } catch (Exception e) { } } } D:\psr\J2EE>javac ClsOne.out.it is machine generated */ #include <jni.java D:\psr\J2EE>javah ClsOne D:\psr\J2EE>type ClsOne.h /* DO NOT EDIT THIS FILE . } public native void mtwo( ).int) int sub(int. jobject).46 System.int j) { int res=i-j. return res. } math. } int sub(int i. return res.loadLibrary("ourfuncs").c int add(int i.int j) { int res=i+j.int) Prototype of function .

mtwo is declared as native.h C/C++ code for the functions (Java_ClsOne_mtwo) ourfuncs. so=stored object.c C compiler & (+) limker m/l (machine language instructions) for the functions provided in C/C++ ) ourfuncs.so Windows Unix/Linux dll=dynamic link library.java javac ClsOne.dll/ourfuncs. ClsOne.47 Implementation of function We can use JNI technology for implementing the java code that can use the code implemented in C/C++ languages.Class javah Properties of the functions ClsOne. 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). We must provide the code for this method in ‘C’ language. From the ‘C’ code the .

} .driver.jdbc.driver. D:\psr\J2EE>set CLASSPATH=ojdbc14.48 native API’S of the databases will be used (OCI in case of Oracle Driver. Connection con=DriverManager.println("----Connected----")."system".forName("oracle.jar. System. For using Type II Driver net service name Provided by Oracle Corp. Java classes Code for imple in C lang dll files OCI in case of Oracle/ MySql C API in case of MySql. Type II Driver provided by Oracle Corporation is called as OCI Driver by Oracle. Type II Driver is not a pure java driver..import java. Native API of DB 1) Set the CLASSPATH pointing to the jar file that contains the classes of the JDBC driver. "tiger"). We can use code as shown below for using the Type II Driver provided by Oracle Corporation. MySql C API in case of MySql). Connection con=DriverManager.out.getConnection ("jdbc:oracle:oci:@orans". Oracle Corp as they internally use OCI functions.OracleDriver"). public class Type2 { public static void main(String args[]) throws Exception { Class.OracleDriver ").forName("oracle."scott". Ex: . the dll files that contains OCI API & the dll’s that contains the ‘C’ code used from the java classes will be copied). If an application uses Type II Drivers."sunil"). 3) Configure the client software (this is generally carried out by the database administrator).sql. the following Steps must be performed.getConnection ("jdbc:oracle:oci:@orans". 2) Install the client software (when we install Oracle client software.  class.*.jdbc.

"scott".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. Note: .getConnection ("jdbc:oracle:thin:@localhost:1521:xe".forName("oracle.*. the CLASSPATH must be set to point to the jar file that contains the class files of the driver.forName("oracle.jdbc.OracleDriver"). System.In case of Type IV Driver.As configuring the software that uses Type IV Driver & the modern JVM’S uses various optimization technologies to improve the speed of running the byte code. ODBC: .jdbc.Open database connectivity (OJDBC) API: - . D:\psr\J2EE>javac Type2. It is a pure java driver..49 } D:\psr\J2EE>set CLASSPATH=ojdbc14. Most of the developers are preparing Type IV Drivers.println("---Connected---")."sunil"). We can use code as shown below for using the Type IV Driver provided by Oracle Corporation.driver.driver. Connection con=DriverManager."tiger").getConnection ("jdbc:oracle:thin:@localhost: 1521:xe".  class.out. Oracle Corporation refers to its Type IV Drivers as thin driver. } } D:\psr\J2EE>javac Type4. To run the application that uses Type IV Driver.sql. the whole code is provided in java language."system".jar.import java.java D:\psr\J2EE>java Type2 ---Connected--Type IV Driver: . Ex: . public class Type4 { public static void main(String args[]) throws Exception { Class.OracleDriver"). Connection con=DriverManager.

sql Connect(…) { olog(…. As part of ODBC specification.. Internally java soft has implemented Type I Driver as implementing.(JDBC – ODBC bridge).). …. …. 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) .50 ODBC API is an open specification.). } …. …. sql Connect(…) { Mysql_connect(…. 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. } Compiler + linker ora... It is easy & the ODBC drivers are available for almost every database. sql disconnect(…) { Mysql_close(…. sql disconnect(…) { olofoff(…. …. ….).. Java classes ‘C’ code ODBC API Native API (OCI etc) In order to use Type I Drivers we must follow the steps given below. } ….dll (ODBC Driver for MySql) Type I Driver: .). Any one can provide the implementation of ODBC Drivers. Micro Soft has provided the information regarding several functions in ‘C’ language. This driver is not a pure java driver..dll (ODBC Driver for Oracle) mysql. } Compiler + linker ….

Configure the ODBC driver. Code for using Type I Driver. "tiger").getConnection("jdbc:odbc:orads".forName("sun."scott". Type III drv . provided by java soft. 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.sql. Connection con=DriverManager.51 2) 3) 4) 5) Install the client software. public class Type1 { public static void main(String args[]) throws Exception { Class.JdbcOdbcDriver "). } } D:\psr\J2EE>javac Type1.jdbc.java D:\psr\J2EE>java Type1 ---Connected--Type III Driver: . Data source name given while Configuring ODBC Driver Ex: .  class.forName("sun.getConnection ("jdbc:odbc:orads".It is pure java drivers. Configure the client software.JdbcOdbcDriver"). Install the ODBC driver.println("---Connected---").out. System.*.odbc. Connection con = DriverManager.jdbc.odbc.import java."sunil")."system".

.52 Serialization: .io. These interfaces are called as tagged interfaces or marker interfaces..Remote …..... java. // CarB objects are Serializable. } public void displayState( ) { if(isOn==true) { System.println("---TLight is on---"). 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.Serializable.In java we can have interfaces without methods.Serializable { .io. A tagged interface is mint for providing some sort of information about an object. public class TLight implements Serializable { private boolean isOn=false... } public void switchoff( ) { isOn=false.. Etc are examples of tagged interfaces.println("---Tlight is off---").  import java. } } } D:\psr\J2EE>javac TLight.rmi. java.out.java ..out. // CarA objects are not Serializable } public class CarB implements java. } else { System..io.. public void switchOn( ) { isOn=true. } An object that implements Serializable interface is called as Serializable object.. For every object there will be a state.  public class CarA { ..Serializable...

} else { System. public void switchOn( ) { isOn=true. } public void displayState( ) { if(isOn==true) { System.53  public class ATLight { private boolean isOn=false. TLight t1=new TLight( ).println("---Tlight is off---"). ObjectOutputStream oos=new ObjectOutputStream(fos). } public void switchoff( ) { isOn=false.*.out.io.out. } } } D:\psr\J2EE>javac ATLight. . public class SerApp { public static void main(String[] args) throws Exception { FileOutputStream fos=new FileOutputStream("test.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.ser").println("---TLight is on---").

ObjectOutputStream oos=new ObjectOutputStream(fos).io.ser"). oos. public class SerApp1 { public static void main(String[] args) throws Exception { FileOutputStream fos=new FileOutputStream("test1.io.close( ).╕ε↔¼"☻ ☺Z ♦isOnxp☺ When oos.ser ¼φ ♣sr ♠TLight‼i.writeObject(Unknown Source) at SerApp1.lang. } } D:\psr\J2EE>javac SerApp1.java D:\psr\J2EE>java SerApp ---TLight is on--D:\psr\J2EE>type test. oos.displayState( ).io.io.java D:\psr\J2EE>java SerApp1 ---TLight is on--Exception in thread "main" java.switchOn( ). DeSerialization: .displayState( ).java:11) D:\psr\J2EE>type test1.io.switchOn( ).NotSerializableException: ATLight at java.ObjectOutputStream. oos.ObjectOutputStream.close ( ).main(SerApp1.writeObject(t1). } } D:\psr\J2EE>javac SerApp. t1.IOExceptionlÇsde%≡½☻ xr‼java.NotSerializableException(Vx τå▬5☻ xr↔java.writeObject(t1). oos.ObjectStream Exceptiond├Σkì9√▀☻ xr ‼java.io. Exception╨²▼> If the object that is passed as a parameter is not serializable then an exception will be thrown by writeObject( ) method.ser ¼φ ♣{sr java.io. t1.It is the process of reading the information about (state) of the object from a stream & creating on object using the information. ATLight t1=new ATLight( ).writeObject0(Unknown Source) at java.54 t1. t1.*.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. .

Thread. } public void displayState( ) { System.io.ser"). Object o=ois.Socket(). java.readObject( ). java.Socket sock. tl.55  import java. } } D:\psr\J2EE>javac TLight1. public class SerApp2 { public static void main(String[] args) throws Exception { FileOutputStream fos=new FileOutputStream("test2.sql.Serializable. Ex:  import java. tl=(TLight)o. } } D:\psr\J2EE>javac DSerApp.ser").println("sock-->"+sock). java.out. public class TLight1 implements Serializable { private boolean isOn.*.lang.io.Connection etc… objects are not serializable.io.net. isOn=true.java D:\psr\J2EE>java DSerApp ---TLight is on--java.Socket. ObjectInputStream ois=new ObjectInputStream(fis). public void setState( ) { sock=new java.*. TLight tl=null.java  import java.out. public class DSerApp { public static void main(String[] args) throws Exception { FileInputStream fis=new FileInputStream("test.net.displayState( ).println("isOn-->"+isOn). .net. System.

56 ObjectOutputStream oos=new ObjectOutputStream(fos). oos.Socket at DSerApp2.NotSerializableException: java.net. tl=(TLight1)o. oos.main(SerApp2.Socket at SerApp2. ObjectInputStream ois=new ObjectInputStream(fis).io. } } D:\psr\J2EE>javac SerApp2.io.main(SerApp2. java.java:11) isOn= true sock TLight1 sock . t1.net. io.net.*.readObject( ).close( ). TLight1 t1=new TLight1( ).java:11)  import java. tl.writeObject(t1). t1.java D:\psr\J2EE>java SerApp2 isOn-->true sock-->Socket[unconnected] Exception in thread "main" java.displayState( ). Object o=ois. TLight1 tl=null.NotSerializableException: java.main(DSerApp2.ser").setState( ).Socket at SerApp2.displayState( ). } } D:\psr\J2EE>javac DSerApp2.io.java:9) Caused by: java.io.NotSerializableException: java. public class DSerApp2 { public static void main(String[] args) throws Exception { FileInputStream fis=new FileInputStream("test2.java D:\psr\J2EE>java DSerApp2 Exception in thread "main" java.WriteAbortedException: writing aborted.

 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. System. public class TLight1 implements Serializable { private boolean isOn. isOn=true. } public void displayState( ) { System. static int notl=0.netSocket) then we must declare the variable as transient.net. } } D:\psr\J2EE>javac TLight1. public void setState( ) { sock=new java.println("sock-->"+sock).  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.out.println("isOn-->"+isOn).net. . System.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. transient java.Serializable.  import java. notl=10.57 Serialization of TLight1 object fails as the sock variable points to a Socket object.Socket( ).println("notl-->"+notl).io.Socket sock.out. non transient variables will be serialized. Which is not Serializable? We can solve the above problem by declaring the instance variable sock as transient.out.

java  import java. isOn=in.io.58 Ex: .writeBoolean(isOn).import java.writeInt(notl).*. static int notl=0. public class DSerApp { public static void main(String[] args) throws Exception { FileInputStream fis=new FileInputStream("test2.readInt( ).println("---our read object---"). notl=in.ser"). oos.*. . private void writeObject(ObjectOutputStream out) throws IOException { System.out. TLight2 t1=new TLight2( ).io. public class TLight2 implements Serializable { private boolean isOn=true. } } D:\psr\J2EE>javac TLight2. oos.ser").writeObject( ) is called it internally uses the code implemented in C (consider to be part of JVM).writeObject(t1).close( ).readBoolean( ). ClassNotFoundException { System.java D:\psr\J2EE>java SerApp ---our write object-- import java.*. out. This code calls writeObject( ) method provided by us in our class. public class SerApp { public static void main(String[] args) throws Exception { FileOutputStream fos=new FileOutputStream("test2. } } When oos. out.io.out. ObjectOutputStream oos=new ObjectOutputStream(fos). } private void readObject(ObjectInputStream in) throws IOException.println("---our write object---"). D:\psr\J2EE>javac SerApp.

readObject( ). The entity beans of EJB 3. To access the data available in a table using Hibernate. To simplify the development of application instead of using JDBC API directly we can use JDO (java data object). ois.x java soft has re-designed the entity beans & this designed is similar to Hibernate. } } When ois.59 ObjectInputStream ois=new ObjectInputStream(fis). we need to provide POJO (plain old java object).x can be used only as part of EJB applications. it internally uses code implemented in C (consider to be part of JVM). The Entity Beans (EJB) that are part of EJB 1. hbm (hibernate mapping) file.students.empNo=empNo. This code calls read object method provided by us in our calls. As part of EJB 3. Hibernate etc… These products are called as ORM (object relational mapping) products.java D:\psr\J2EE>java DSerApp ---our read object--Java soft has defined as a format called java Serialization protocol. If we want to store the information about the object in our format then we must implement java. employee empno 1 2 3 ename EOne ETwo EThr salary 10000 20000 30000 To access the data available in the above table using hibernate. Top Link etc…. public void setEmpNo(Long empNo) { this. When Serializable interface is implemented the information about will be stored using this format. Most of the developers are not using these beans. public class Employee { private Long empno.Externalizable interface.io.0 can be used as part of any kind of java applications. D:\psr\J2EE>javac DSerApp. private String ename. As these entity beans kills the performance of the applications. TopLink.readObject( ) is called.x & 2. we must provide a POJO class as shown below package org. private Double salary. } public Long getEmpNo( ) .

empNo=ename. } public void setEname(String ename) { this.lang.Long java.lang.String java. } public void setSalary(Double salary) { this.60 { return this. } public Double getSalary( ) { return this.empNo=salary.students. } } The above class can consider as java bean also. Property type java.hbm.Double property name empNo ename salary org.students.salary. weblogic workshop etc…for generating 1) POJO classes 2) hbm files 3) hibernate configuration file (cfg) .empNo. We can use the tools like myeclipseide. exader studio.Employee  employee empNoempno eneme  ename salary  salary one. 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.xml hbm files contains the information regarding the mapping between the POJO classes & the tables that has to be access by hibernate.ename. } public String getEname( ) { return this.Employee class supports the following properties.lang.

ename varchar(15). SQL> desc employee.------------------ENO NOT NULL NUMBER ENAME VARCHAR2(15) AGE NUMBER SALARY NUMBER(10.-------. Name Null? Type ----------------------------------------. 5) Click on the ok button in work space launcher.D:\psr\J2EE\eclws) 2) Copy the jdbc driver (ex: .61 SQL> create table employee (eno number primary key.2) SQL> create table product (pid number primary key. prodname varchar(15).price number(10.2)). Name Null? Type ----------------------------------------. 6) Choose My Eclipse database explorer prospective.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. salary number(10. Table created.ojdbc14.2)).2) Procedure for setting up myeclipseide: 1) Create a work space directory (ex: . SQL> desc product. Table created. .---------------------------PID NOT NULL NUMBER PRODNAME VARCHAR2(15) PRICE NUMBER(10.age number.-------.

10) Click on add jar’s button in new driver window & choose the jar file that was copied in step2. 9) Click on the new button in performance window. . 11) Choose oracle thin driver as Driver template & click on OK button in new driver window. 8) Click on “configure database driver” available in profile window.62 7) Right click in DB browser view to get the popup menu & choose new option.

.63 12) Click on OK button in preferences window 13) Provide the information shown below & click on finish button in database profile window.

Procedure for creating a project that uses hibernate: 1) Choose java prospective. 2) Chose file  new  project 3) In new project window choose java project & click on next button.64 Note: . At this information will be use by eclipse to connect to oracle server. .The information providing in the above step will be stored in the files related to myeclipseide.

myeclipseide creates various folders under the workspace directory as shown below D:\ psr J2EE .hibproj. choose create separate source & output folders option & click on finish button) Note: .65 4) In the new project window provide the project name (ex: .

6) In new hibernate project window check all the check boxes & click on the next button. 8) Select oraprof as DB profile & click on next. used for .java files 5) In package explorer choose the project.66 HibProj1 bin src used for . 7) Click on next button.class files. choose myeclipse  & add hibernate capabilities. .

xml 2) oraSF.xml the information that is required to establish the database connections (driver class. Procedure for generating POJO classes & hbm files: 1) Choose myeclipse database explorer in prospective. Note: .java (class name: org.OraSF Note: .students.As part of hibernate. uname. pwd) & the information about hbm files will be provide.cfg.myeclipse creates 1) hibernate. .cfg. url.org.OraSF) & click on finish.students.67 9) Provide SessionFactory class (ex: .

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

2) To create a Session object org.cfg.hibernate. d) Click on finish.xml. 3) To create a SessionFactory object org.myeclipse creates the POJO classes.hibernate. Note: .configuration object is required.students) c) Uncheck create abstract class.Session object is required. hbm files and adds the information about the hbm files to hibernate. 1) In order to use hibernate org.hibernate.SessionFactory object is required. .69 5) In hibernate reverse engineering window a) Click on browse button & choose src folder b) Provide java package (org.cfg.

username">system</property> <property name="connection.xml: .Generated by MyEclipse Hibernate Tools.sourceforge.hibernate.hibernate.profile">orans</property> <property name="connection. --> <hibernate-configuration> <session-factory> <property name="connection.url">jdbc:oracle:thin:@localhost:1521 :xe</property> <property name="dialect">org.driver.0.hibernate.70 drvcls.xml"></mapping> </session-factory> </hibernate-configuration> Employee.xml configure( ) org.(code) <?xml version="1. OracleDriver</property> <mapping resource="org/sunil/Employee.hibernate.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.cfg.password">sunil</property> <property name="connection.0//EN" "http://hibernate.hbm.xml: .0//EN" "http://hibernate.dtd"> <!-- .xml" /> <mapping resource="org/sunil/Product.url … etc + info of hbm files hibernate.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.dialect.jdbc.session hibernate.Oracle9Dialect </property> <property name="myeclipse.connection.hbm.net/hibernate-mapping-3.driver_class">oracle.SessionFactory openSession( ) org.sourceforge.configuration buildSessionFactory( ) Mapping b/w classes & tables … hbm files org.(code) <?xml version='1.uname.cfg.0.pwd.hbm.dtd"> <!-.cfg.net/hibernate-configuration-3.

Hibernate Tools --> <hibernate-mapping> <class name="org.openSession().configure( ). configure( ) method takes more amount of time to read the information (that is configure( ) method is expensive). openSession( ) method creates a Session objects & it is not expensive. // code to perform DB oparations hsession.71 Mapping file autogenerated by MyEclipse . SessionFactory sf=conf.hibernate.sunil.*. } } A business application performs the following 4 operations.store the data (insert) .  package org.close( ). conf.hibernate.sunil.cfg. public class HibApp1 { public static void main(String[] args)throws Exception { Configuration conf=new Configuration( ). 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. import org. import org.buildSessionFactory( ). Session hsession=sf. This operation is expensive & it should be used only once.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.*. This method should be called only once by the application. 1) create –. As there will be lot of information available in these files.

remove the data (delete) The code shown below performs the create operation.hibernate. Commit complete. Employee emp2=new Employee( ).setSalary(10000).*.setAge(23). emp3.*. emp1. emp1.beginTransaction( ). hsession.commit( ). emp2. // code to perform DB oparations Transaction tx=hsession.modify the data (update) 3) read -– get the data (select) 4) delete –. hsession.save(emp3).setSalary(20000).configure( ).setEname("EThr"). emp1.save(emp2). no rows selected SQL> commit. } } SQL> select * from employee.buildSessionFactory( ).setEno(2). emp1. import org.setAge(22). emp3.setEname("ETwo"). import org.setAge(21). public class HibApp1 { public static void main(String[] args)throws Exception { Configuration conf=new Configuration( ). Employee emp1=new Employee( ). emp3. hsession. conf.hibernate. emp2.setEno(1). Session hsession=sf. hsession.setSalary(30000).72 2) update –.openSession( ).sunil.save(emp1). .close( ). emp2.setEname("EOne"). SessionFactory sf=conf.  package org.setEno(3). emp2. Employee emp3=new Employee( ). tx. emp3.cfg.

openSession( ).close( ).out.buildSessionFactory( ).--------------.hibernate. ENO ENAME AGE SALARY ---------. System.  package org. System. System. hsession. import org.*.println(emp. hsession.out.cfg.hibernate.*.println(emp.out. public class HibApp2 { public static void main(String[] args)throws Exception { Configuration conf=new Configuration( ).configure( ).getEname( )).---------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. Session hsession=sf.sunil. // code to perform DB oparations Employee emp=new Employee( ).getAge( )).load(emp.out.---------. System.getSalary( )). SessionFactory sf=conf.println(emp. } } HibApp2  Run As  Java Application 1 EOne . import org.getEno( )).new Long(1)).73 SQL> select * from employee.println(emp. conf.

cache.util. When SessionFactory is created Hashtable kind of class will be used to create an object.put(“KOne”.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. .Hashtable KThr Hibernate internally uses the objects based on the classes similar to Hashtable for holding / caching the java object. java.buildSessionFactory( ).util. This object will be associated with SessionFactory & this object is called as first level cache.“VOne”).openSession( ).“VThr”).put(“KThr”. SessionFactory sf=sf. cache. KOne VOne KTw o VTw o VThr cache Ht Entry java.74 21 10000. The combination of the key & the value is called as hash table entry. For storing any thing in hash table many to use a key & a value.“VTwo”). Hashtable cache=new Hashtable( ). cache.put(“KTwo”. sf cach e Hashtable kind of object First level cache Session hsession=sf.Hashtable can be used any number of & any type of java products.

save(emp). 1) Checks for the objects in the second level cache. 2) Hibernate gets the data from the database & calls the setters on the POJO object to put the data in the object.75 When a Session object is created internally an object similar to Hashtable will be created & it will be associated with Session object.---------1 EOne 21 10000 2 ETwo 22 20000 3 EThr 23 30000 . This is called second level cache.cfg. Note: . 3) Hibernate stores the reference of the POJO object & the second level cache. is executed Hibernate performs the following steps. hsession cach e Hashtable kind of object Second level cache To see the SQL statements that are executed by Hibernate. ENO ENAME AGE SALARY ---------. hsession.--------------.new Long(1)).---------.load(emp.xml <property name= “show_sql”>true </property> When hsession. 4) Commits the transaction. we must add the following line to hibernate. When the load method is executed hibernate performs the following steps: 1) Hibernate executes the select statement. SQL> select * from employee. is executed hibernate stores the reference of employee object in the second level cache as shown in the diagram. 2) Identifies the operations that have to be performed on the database.commit( ). emp hsession cach e Hashtable kind of object Second level cache To be stored 1 EOne 21 10000 Employee When tx. 3) Execute the SQL statements (in the above application insert statement will be executed).Hibernate uses batch update feature or JDBC to improve the performance.

hsession. public class HibApp3 { public static void main(String[] args)throws Exception { Configuration conf=new Configuration( ). 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).EOne. Employee emp1=new Employee( ). conf.beginTransaction( ).hibernate. emp1. emp1.setSalary(26000). hsession.configure( ). emp2.println("----Calling commit----").*. 2--->The data will be obtained [2.10000] & it will be loaded in employee object referred by emp1 & this object will be placed in the cache. } } 1--->The data will be obtained [1.hibernate. SessionFactory sf=conf.commit( ).setSalary(25000).21.76  package org. 3---> When commit is called hibernate identify that there are 2 dirty objects in the cache & it’s execute update statements to modify the data in employee table.new Long(2)).openSession( ).*.cfg. // code to perform DB oparations Transaction tx=hsession.load(emp1.buildSessionFactory( ). Employee emp2=new Employee( ). import org. hsession.22.sunil.load(emp2. . tx.ETwo.setAge(25).out.20000] & it will be loaded in employee object referred by emp2 & this object will be placed in the cache.new Long(1)).close( ). System. Session hsession=sf.setAge(26). emp2. import org.

AGE=?.ENO=? Hibernate: select employee0_.ENAME as ENAME0_0_. --->3 hsession. hsession.*. 2---> The Employee object will be detached from the Session cache.--------------. . import org. --->2 //hsession. SALARY=? where ENO=? SQL> select * from employee. ENO ENAME AGE SALARY ---------.EMPLOYEE set ENAME=?.hibernate. Session hsession=sf.evict(emp1). employee0_. --->1 emp1.EMPLOYEE set ENAME=?.setAge(27). Employee emp1=new Employee( ). emp1. public class HibApp4 { public static void main(String[] args)throws Exception { Configuration conf=new Configuration( ).SALARY as SALARY0_0_ from SYSTEM.*.buildSessionFactory( ).SALARY as SALARY0_0_ from SYSTEM.---------. AGE=?. } } 1---> Employee object will be attaching to the Session cache.EMPLOYEE employee0_ where employee0_.EMPLOYEE employee0_ where employee0_.  package org.cfg.ENAME as ENAME0_0_.setSalary(35000). employee0_.configure( ).ENO as ENO0_.ENO as ENO0_. import org.load(emp1. hsession.sunil. SALARY=? where ENO=? Hibernate: update SYSTEM.AGE as AGE0_0_. employee0_.close( ).ENO=? ----Calling commit---Hibernate: update SYSTEM.---------1 EOne 25 25000 2 ETwo 26 26000 3 EThr 23 30000 evict( ) method is used to detach the object from the session catch. employee0_.new Long(3)). SessionFactory sf=conf.77 HibApp3  Run As  Java Application Hibernate: select employee0_.AGE as AGE0_0_.commit( ).openSession( ). tx. employee0_.beginTransaction( ). employee0_.hibernate. conf.update(emp1). // code to perform DB oparations Transaction tx=hsession.

public class HibApp5 { public static void main(String[] args)throws Exception { Configuration conf=new Configuration( ). import org. HibApp4  Run As  Java Application Hibernate: select employee0_.load(emp2.configure( ). employee0_.*. employee0_. SessionFactory sf=conf.ENAME as ENAME0_0_. employee0_.delete(emp2). // code to perform DB oparations Transaction tx=hsession. employee0_. hsession.setSalary(18000).78 3---> update statement will be not being executed as the Employee object is not available in the Session cache. hsession.AGE as AGE0_0_. Employee emp1=new Employee( ). import org.---------& 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. employee0_. tx.update(emp1).AGE as AGE0_0_.hibernate.  package org.reattach ---------. emp1.SALARY .beginTransaction( ).buildSessionFactory( ).openSession( ). employee0_.setEno(1). conf. Employee emp2=new Employee( ).detach ENO ENAME AGE SALARY Update --.setEname("Sudheer").ENAME as ENAME0_0_.setAge(23). hsession.ENO as ENO0_. emp1. } } HibApp5  Run As  Java Application Hibernate: select employee0_.---------.close( ).sunil.cfg. hsession.SALARY as SALARY0_0_ from SYSTEM.ENO=? Load --.commit( ). An application can use delete( ) method to ask hibernate to delete the data from database.EMPLOYEE employee0_ where employee0_.attach SQL> select * from employee.new Long(3)). emp1. Evict --. emp1.ENO as ENO0_. Session hsession=sf.*.--------------.hibernate.

If the data type of a property in a POJO class is primitive data type & if the column.lang.EMPLOYEE where ENO=? SQL> select * from employee. public double getSalary( ) { return this.---------------.'EThr'). invalid.EMPLOYEE employee0_ employee0_. ENO ENAME AGE SALARY ---------. that is mapped to the property contains null. public class Employee { ……. double salary. SALARY=? where ENO=? Hibernate: delete from SYSTEM.----------------. int etc var’s (primitive data types) to null Long vtwo=null.79 as SALARY0_0_ from SYSTEM. we can set long. To avoid this problem we can use the wrapper classes of primitive data types like java.  valid.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. 1 row created. ENO ENAME AGE SALARY ---------. Then hibernate will fail as it can not set null in the primitive data type variable.----------3 EThr 1 Sudheer 23 18000 2 ETwo 26 26000 long vone=null.EMPLOYEE set ENAME=?. Note: .ename) values (3. } } 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.salary. SQL> select * from employee.Double etc… as the data types of the properties in the POJO classes. where AGE=?.Long.-----------------.salary = salary.ENO=? Hibernate: update SYSTEM.-------------1 Sudheer 23 18000 2 ETwo 26 26000  SQL> insert into employee (eno.--------------------------. . java. } public void setSalary(double salary) { this.lang.

In case of form two end user need not provide the value of Emp no on his own. we must specify the generator tag in the id tag as shown below. In this case the application must generate the value of Emp no. As part of the hbm file.80 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. <id name="eno" type="java.Long"> <column name="ENO" precision="22" scale="0" /> <generator class="assigned" /> </id> .lang. Hibernate supports various ways / strategies / algorithms for generating the value of the primary key fields.

emp1. Employee emp2=new Employee( ). SQL> commit.setSalary(new Double(30000)).*. conf.openSession( ).81 The value of the Eno must be set (assigned) by the application before calling save method.sunil. public class HibApp6 { public static void main(String[] args)throws Exception { Configuration conf=new Configuration( ). guid (globally unique id).hibernate.setEname("Sunil"). Commit complete. .setAge(new Long(23)). Employee emp1=new Employee( ).configure( ). SessionFactory sf=conf.2 : when save method is called hibernate generates the value of Eno automatically.setSalary(new Double(20000)).buildSessionFactory( ). 3 rows deleted.commit( ). Session hsession=sf. hsession. emp2. import org.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. emp1. import org. Hibernate generates the value of Eno in this case.setAge(new Long(24)). SQL> delete from employee.*. no rows selected  package org. --.save(emp1).beginTransaction( ). emp1.setEname("Sudheer"). } } Assumption: . // code to perform DB oparations Transaction tx=hsession.> 1 hsession.hibernate.close( ).<generator class = “increment”/> is used 1.save(emp2).> 2 tx. hsession. emp2.lang. emp2. Like increment hibernate supports hilo. --.cfg. SQL> select * from employee. <id name="eno" type="java. native (Oracle : Hibernate uses sequences for generating the value for the column) (MySql: Hibernate uses auto increment feature supported by MySql).

addrno)).82 HibApp6  Run As  Java Application SQL> select * from employee. SQL> create table eddrs (eno number(4). ENO ENAME AGE SALARY ---------. city varchar(10). 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.Hibernate manuals recommends that we must avoid the tables with multiple columns in primary key. primary key (eno. SQL> desc eddrs.------------------. addrno number(4). state varchar(10).--------------------. Table created. In this case we must provide a PRIMARY KEY Class. We may need to used tables with multiple columns in primary key while developing the apps using legacy database.--------------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: . street varchar(10). .

pk2.configure( ).hashcode( ) method should return the same value for two different objects that represents the same primary key. public class HibApp7 { public static void main(String[] args)throws Exception { Configuration conf=new Configuration( ).setEno(new Long(1)). import org. the following 2 classes must be used.*.buildSessionFactory( ).We must use <composite-id> tag instead of <id>tag in the hbm file.cfg.We need to follow the recommendations given below while providing the primary key class.-------. Session hsession=sf. PRIMARY KEY Class . pk1. conf. id Eaddrsid street String city String state String eno Long addrno Long Eaddrsid Eaddrs Note: . pk1. 1) The class must implement java. SessionFactory sf=conf. both the objects represents the same primary key otherwise it must return false. import org.io.hibernate.  package org. Note: .Serializable interface.setEno(new Long(1)).setAddrno(new Long(1)). // code to perform DB oparations Transaction tx=hsession.beginTransaction( ). EddrsId pk2=new EddrsId( ).hibernate. 3) Provide equals & hash code methods.openSession( ). Note: .sunil. EddrsId pk3=new EddrsId( ).setAddrno(new Long(2)). 2) The class must support the properties that must be mapped to the columns of the primary keys. EddrsId pk1=new EddrsId( ). pk2.*.equals( ) method should return true. Note: .---------------------------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.83 Name Null? Type ----------------------------------------.

Our code must provide a statement in HQL to hibernate.equals(pk3)). pk3.println(pk1. System.84 pk3. } } HibApp7  Run As  Java Application pk1--->23311 pk2--->23312 pk3--->23312 false true Hibernate supports hibernate query language.out.equals(pk2)).setAddrno(new Long(2)). org. System. System. System. While converting hibernate takes care of the differences in the SQL that is supported by various data types.println("pk3--->"+pk3.println("pk1--->"+pk1.out. tx.out. Hibernate converts HQL to SQL.println("pk2--->"+pk2.hashCode( )).out.out.Employee  empNo empName empAge empSalary employee eno ename age salary     Property names Column names .hashCode( ))..println(pk2. System.hashCode( )).close( ).commit( ). 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. hsession.setEno(new Long(1)).sunil.

age number(4).sunil. SQL> insert into employee values (1.'EFour'.'EOne'. HQL: . Commit complete.-------------------1 EOne 21 10000 2 ETwo 22 20000 3 EThr 23 30000 4 EFour 24 40000 5 EFive 25 50000 SQL> commit. 1 row created.30000). ENO ENAME AGE SALARY ---------. SQL> insert into employee values (4. 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.'EFive'.23.As part of the HQL we must use the names of the POJO classes instead of the names of the tables. salary number(10. 1 row created.from org.'ETwo'.24. 1 row created. SQL> select * from employee. SQL> insert into employee values (3.25.2)). SQL> insert into employee values (2. As part of the SQL we can use the property names instead of the column names. 1 row created.--------------.22.select * from employee.10000). Table created.--------------. ename varchar(15).20000). Table name SQL: .Employee Name of the POJO class mapped to employee table.21. .'EThr'. SQL> insert into employee values (5.50000).85 Note: .40000). 1 row created.

0 2 ETwo 22 20000.100. System.*. When qry. HibApp8  Run As  Java Application 1 EOne 21 10000.getEno( )). import java.*.list( ) is executed the following steps carried out by hibernate.'pen'.out.util.openSession( ).getAge( )).print("\t"+e.i<empList.Employee".print("\t"+e. Session hsession=sf. import org.out. SessionFactory sf=conf. 1) HQL will convert into SQL. System.buildSessionFactory( ). 5) The list of objects will be attached to the Session cache. 4) Creates five employee objects.list( ).list( ). List empList=qry.getEname( )). import org.hibernate. conf.00).print(e.hibernate.commit( ).out. Employee e=(Employee)o. public class HibApp8 { public static void main(String[] args)throws Exception { Configuration conf=new Configuration( ). } tx. hsession. } } The code shown above gets the data from employee table & generates reports based on the information.println("\t"+e. 1 row created.0 3 EThr 23 30000.0 4 EFour 24 40000. 2) SQL will be executed. Query qry=hsession. // code to perform DB oparations Transaction tx=hsession. .get(i). List empList=qry.configure( ). and places the employee objects inside a list object. System. for(int i=0.close( ).createQuery(vhql).i++){ Object o=empList.0 5 EFive 25 50000. loads the data in employee object. String vhql="from org.beginTransaction( ). System.cfg. 3) Data will be obtained from the database table employee.out.sunil.sunil.0  SQL> insert into product values (1.getSalary( )).*.86  package org.size().

*.87 SQL> insert into product values (2. Boolean b[]=new Boolean[10].buildSessionFactory( ).sunil. // code to perform DB oparations Transaction tx=hsession.  package org. import org.hibernate.------------------1 pen 100 2 pencil 50 SQL> commit. Integer i[][]=new Integer[10][10].00). SQL> select * from product. hsession. for(int i=0. Session hsession=sf. .get(i). public class HibApp9 { public static void main(String[] args)throws Exception { Configuration conf=new Configuration( ). conf.sunil.configure( ).i<prodList.openSession( ).50. Commit complete.cfg. String vhql="from org.*.'pencil'.close( ).commit( ).*. We can use the code shown below to remove all the rows from product table.util. import java. } tx. SessionFactory sf=conf.hibernate. no rows selected  class ArrayApp { public static void main(String[] args) { Object o[][]=new Object[10][10].size( ). hsession.Product". List prodList=qry. Query qry=hsession.delete(p).------------------.beginTransaction( ). 1 row created. import org.i++){ Product p=(Product)prodList. } } HibApp9  Run As  Java Application SQL> select * from product.list( ).createQuery(vhql). PID PRODNAME PRICE ---------. Byte by[]=new Byte[10].

@10b62c9 [[Ljava.out.88 System. for(int i=0.@923e30 [Ljava.println("-------").configure( ).openSession( ).ename. .out.java D:\psr\J2EE>java ArrayApp [[Ljava.lang.Employee as e".e. import org.hibernate.beginTransaction( ).cfg. SQL> select e.*. ENAME SALARY --------------.*.out.i<empList. import java.get(i). Object arr[]=(Object[])o.sunil.salary from employee e. [=single dimensional array.println(arr. import org.Boolean. System.*.lang. conf.Byte.out.println(arr[0]).@82ba41 [Ljava. System.println(arr[2]).println(o).out.lang. List empList=qry. String vhql="select e.buildSessionFactory( ).out. System.println(b).length).out. System.ename. e.lang.Object.out.Integer.list( ).util.out.i++){ Object o=empList. // code to perform DB oparations Transaction tx=hsession.createQuery(vhql).@130c19b Here [[=multi dimensional array.println(i). public class HibApp10 { public static void main(String[] args)throws Exception { Configuration conf=new Configuration( ). System. System. Query qry=hsession.size( ).e.salary. Session hsession=sf. System.-------------------EOne 10000 ETwo 20000 EThr 30000 EFour 40000 EFive 50000  // Here e means Elias.println(by).sunil.println(arr[1]). } } D:\psr\J2EE>javac ArrayApp.hibernate. System. SessionFactory sf=conf.  package org.age from org.

0 24 ------3 EFive 50000.89 } tx. hsession.0 21 ------3 ETwo 20000.0 22 ------3 EThr 30000. } } HibApp10  Run As  Java Application EOne 10000.commit( ). EOne 10000 21 ESix 60000 Object [] length=3 List 26 Object [] length=3 Get employee details .0 23 ------3 EFour 40000.close( ).0 25 ------3 As 3 properties are chosen hibernate creates a single dimension object array for every row & the size of the array 3.

*.util.90 SQL> insert into employee values (6.'ESix'.configure( ).*.getEname( )).cfg.---------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. System. String vhql="from org.60000).salary<=?". List empList=qry.--------------------.salary>=? and e. Session hsession=sf.out. qry.hibernate.get(i). . SQL> select * from employee. public class HibApp11 { public static void main(String[] args)throws Exception { Configuration conf=new Configuration( ). 1 row created. SessionFactory sf=conf. System.setString(0.out. qry.println(emp.i<empList.size( ). Employee emp=(Employee)o.list( ).buildSessionFactory( ). import org.println(emp.26."40000").println(emp.out. ENO ENAME AGE SALARY -----------.setString(1. System."20000").sunil. conf.getEno( )).getSalary( )).out. // code to perform DB oparations Transaction tx=hsession.println(emp.beginTransaction( ).hibernate.getAge( )).i++){ Object o=empList. for(int i=0.---------------------.createQuery(vhql).sunil.*. System. import java. Query qry=hsession.Employee as e where e.openSession( ). import org.

"20000"). The relationship between empaddrs & employee is many-to-one. many-to-many.createQuery(vhql). } tx."40000").is called as positional parameter. Query qry=hsession. } } Here ? ---. Here minsal & maxsal are called names of the parameters. as part of our application to get the results similar to the above application.setString(“maxsal”.commit( ).0 ------4 EFour 24 40000.0 ------We can use the object of type restriction criteria. List empList=qry. hsession.println("-------").list( ).Employee as e where e. qry. // code same as earlier application. Hibernate can automatically manage one-to-one.sunil. As shown the figure.salary<=:maxsal". HibApp11  Run As  Java Application 2 ETwo 22 20000. one-to-many.out. In place of positional parameter.setString(“minsal”. we can use the named parameters to improve the readability of the code. .  The relationship between employee & empaddrs is one-to-many.salary>=:minsal and e.0 ------3 EThr 23 30000.91 System.  String vhql="from org. many-to-one.close( ). qry.

city varchar(10)). addrno number(1).92 Employee 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. street varchar(10). 1 EOne 21 10000 Set Employee Empaddrs Empaddrs Property name eno ename salary age empaddrs Type long String Double Long Set Get Empaddrs & set Empaddrs is for maintaining The relationship with the Rows of Empaddrs table. salary number(10.sunil.Employee . age number(3). empno number(4) references employee(eno). Table created. ename varchar(10).2)). SQL> create table empaddrs (aid number(4) primary key. Table created. org.

setEno(new Long(1)).setStreet("SOne"). ea1. emp. ea1=new Empaddrs( ).sunil. Empaddrs ea1.setSalary(new Double(10000)).sunil. ea1.  package org. many-to-one are used in the hbm files to specify the type of relationships that exists between various entities. emp.The tags like one-to-many.setAge(new Long(21)).ea2. import org. Session hsession=sf.util.*. .hibernate.ea2=new Empaddrs( ).Empaddrs Note: . ea1. public class HibApp12 { public static void main(String[] args)throws Exception { Configuration conf=new Configuration( ).beginTransaction( ). conf.openSession( ). // code to perform DB oparations Transaction tx=hsession. Employee emp=new Employee( ).setAid(new Long(1)).*.*.buildSessionFactory( ).cfg.hibernate.93 1 1 SOne COne Empaddrs 1 EOne 21 10000 Employee Property name aid addrno street City employee Type Long Long String String Employee Used to manage the Relationship with employee Data org.setAddrno(new Long(1)). emp.configure( ). emp. SessionFactory sf=conf.setEname("EOne"). import java. import org.

94 ea1.setCity("COne"); ea2.setAid(new Long(2)); ea2.setAddrno(new Long(2)); ea2.setStreet("STwo"); ea2.setCity("CTwo"); ea1.setEmployee(emp); ea2.setEmployee(emp); Set eaSet=new HashSet( ); eaSet.add(ea1); eaSet.add(ea2); emp.setEmpaddrses(eaSet); hsession.save(emp); tx.commit( ); hsession.close( ); } } HibApp12  Run As  Java 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

95 ** What is lazy fetching & immediate / eager / aggressive fetching? A) package org.sunil; import org.hibernate.*; import org.hibernate.cfg.*; import java.util.*; public class HibApp13 { public static void main(String[] args)throws Exception { Configuration conf=new Configuration( ); conf.configure( ); SessionFactory sf=conf.buildSessionFactory( ); Session hsession=sf.openSession( ); // code to perform DB 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

96 ----calling get City---CTwo 2 ETwo 22 20000.0 4 EFour 24 40000.0 If aggressive loading strategy is used hibernate loads the data from employee table & empaddrs table when qry.list( ) is executed. In case of the above application hibernate waste time by loading the data from empaddrs table. Note: - For using immediate loading the following tag must be used in employee.hbm.xml. <set name="empaddrses" inverse="true" cascade="all" lazy="true"> If lazy=“true” is used hibernate uses lazy loading strategy. In this case hibernate gets the data from employee table only when qry.list( ) executed. When lazy loading is used hibernate to loads the data from the associated table only, if it is required / accessed. Most of the application will be benefited by lazy loading strategy.  A design pattern is a good solution for re-occurring problem. Singleton design pattern: Maintain only one object based on a class is called as singleton. As it is not recommended to repeatedly call configure( ) method & buildSessionFactory( ) method. It is recommended to maintain one instance (singleton) of SessionFactory. We can use the class shown below for maintaining a singleton of type SessionFactory.  We can use the code shown below to deal with the database using Hibernate. Session hsession=org.sunil.OraSF.currentSession( ); // code to deal with 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;

} return emp. static { emp=new Employee( ). } } (or) public class Employee{ private satatic Employee emp=null. public static Employee createEmp( ) { if(emp=null) { emp=new Employee( ).97 } } }  public class Employee{ private satatic Employee emp=null. } public static Employee createEmp( ) { return emp. } } .