61
Copyright © 2008, Infosys Technologies Ltd. Confidentia l Persistence Tier using Oracle and JPA-Day 3 ER/CORP/CRS/ED111/003 Ver. No.: 1.0 Copyright © 2008, Infosys Technologies Ltd. Education and Research We enable you to leverage knowledge anytime, anywhere! Confidentia l

Slides persistence tier using oracle and jpa ed111_03

Embed Size (px)

DESCRIPTION

 

Citation preview

Copyright © 2008, Infosys Technologies Ltd. Confidential

Persistence Tier using Oracle and JPA-Day 3Persistence Tier using Oracle and JPA-Day 3

ER/CORP/CRS/ED111/003ER/CORP/CRS/ED111/003 Ver. No.: 1.0Ver. No.: 1.0 Copyright © 2008, Infosys Technologies Ltd.Copyright © 2008, Infosys Technologies Ltd.

Education and Research We enable you to leverage knowledge anytime, anywhere!

Confidential

Copyright © 2008, Infosys Technologies Ltd. Confidential

General GuidelineGeneral Guideline

© (2008) Infosys Technologies Ltd.

This document contains valuable confidential and proprietary information of Infosys. Such confidential and proprietary information includes, amongst others, proprietary intellectual property which can be legally protected and commercialized. Such information is furnished herein for training purposes only. Except with the express prior written permission of Infosys, this document and the information contained herein may not be published, disclosed, or used for any other purpose.

22

Copyright © 2008, Infosys Technologies Ltd. Confidential

Confidential InformationConfidential Information

This Document is confidential to Infosys Technologies Limited. This document contains information and data that Infosys considers confidential and proprietary (“Confidential Information”).

Confidential Information includes, but is not limited to, the following: Corporate and Infrastructure information about Infosys Infosys’ project management and quality processes Project experiences provided included as illustrative case studies

Any disclosure of Confidential Information to, or use of it by a third party, will be damaging to Infosys.

Ownership of all Infosys Confidential Information, no matter in what media it resides, remains with Infosys.

Confidential information in this document shall not be disclosed, duplicated or used – in whole or in part – for any purpose other than reading without specific written permission of an authorized representative of Infosys.

This document also contains third party confidential and proprietary information. Such third party information has been included by Infosys after receiving due written permissions and authorizations from the party/ies. Such third party confidential and proprietary information shall not be disclosed, duplicated or used – in whole or in part – for any purpose other than reading without specific written permission of an authorized representative of Infosys.

33

Copyright © 2008, Infosys Technologies Ltd. Confidential44

Recap Recap

Triggers

Packages

Data Transfer Utilities

Copyright © 2008, Infosys Technologies Ltd. Confidential55

Session PlanSession Plan

• JDBC

• Introduction to Java Persistence API (JPA)

Copyright © 2008, Infosys Technologies Ltd. Confidential66

Persistence Tier (JDBC/JPA)Persistence Tier (JDBC/JPA)

Copyright © 2008, Infosys Technologies Ltd. Confidential

JDBCJDBC

ER/CORP/CRS/ED111/003ER/CORP/CRS/ED111/003 Ver. No.: 1.0Ver. No.: 1.0 Copyright © 2008, Infosys Technologies Ltd.Copyright © 2008, Infosys Technologies Ltd.

Education and Research We enable you to leverage knowledge anytime, anywhere!

Confidential

Copyright © 2008, Infosys Technologies Ltd. Confidential88

JDBC JDBC

The JDBC (Java Database Connectivity) API helps a Java program to access a database in a standard way

JDBC is a specification that tells the database vendors how to write a driver program to interface

Java programs with their database tells the programmers how to write a Java program to access any

database A Driver written according to this standard is called the JDBC

Driver

All related classes and interfaces are present in the java.sql package

All JDBC Drivers implement the interfaces of java.sql

Copyright © 2008, Infosys Technologies Ltd. Confidential99

JDBC Architecture and Drivers JDBC Architecture and Drivers

Java Application

JDBC Driver Manager

JDBC/ODBCBridge

Vendor-suppliedJDBCDriver

ODBCDriver

JDBC API

JDBC DriverAPI

Four types of drivers

Type 1 Driver or JDBC-ODBC Bridge Driver

Type 2 Driver or Native-API Driver

Type 3 Driver or Network-Protocol Driver

Type 4 Driver or Native-Protocol Driver

Copyright © 2008, Infosys Technologies Ltd. Confidential

Comparison Between DriversComparison Between Drivers

1010

  Also known as Conversion styleIs it pure

java Dependencies

Type 1JDBC-ODBC

BridgeJDBC method calls into ODBC function calls No Yes

Type 2Native-API

driverJDBC method calls into native calls of the database API No Yes

Type 3Network-Protocol

Driver

Middle-tier (application server) converts JDBC calls directly or indirectly into the vendor-specific database protocol Yes No

Type 4Native-Protocol

Driver JDBC calls directly into the vendor-specific database protocol Yes No

Copyright © 2008, Infosys Technologies Ltd. Confidential1111

Database Interaction in JDBC Database Interaction in JDBC

The steps involved in a database interaction are:– Loading the specific driver– Making a connection to the database– Sending SQL statements to the database– Processing the results

Copyright © 2008, Infosys Technologies Ltd. Confidential1212

Loading the Database Driver Loading the Database Driver

We load the driver class by calling Class.forName() with the Driver class name as an argument.

Once loaded, the Driver class creates an instance of itself.

The General format is : Class.forName( String ClassName );

Class is a class in java.lang package.

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

Copyright © 2008, Infosys Technologies Ltd. Confidential1313

DriverManager class DriverManager class

Manages all the JDBC Drivers that are loaded in the memory

Helps in dynamic loading of Drivers

Its getConnection() method is used to establish a connection to a database.

It uses a username, password, and a jdbc url to establish a connection to the database and returns a connection object.

Copyright © 2008, Infosys Technologies Ltd. Confidential1414

Connection interfaceConnection interface

Defines methods for interacting with the database via the established connection.

A connection object represents a connection with a database.

A connection session includes the SQL statements that are executed and the results that are returned over that connection.

A single application can have one or more connections with a single database, or it can have many connections with many different databases.

Example :Connection connection = DriverManager.getConnection( "jdbc:oracle:thin: @10.122.130.31:1521:training",“scott", “tiger");

Copyright © 2008, Infosys Technologies Ltd. Confidential1515

Creating a Statement object Creating a Statement object

Once a connection is obtained we can interact with the database.

Connection interface defines methods for interacting with the database via

the established connection.

To execute SQL statements, we need to instantiate a Statement object from

the connection object by using the createStatement() method.

Statement statement = connection.createStatement();

A statement object is used to send and execute SQL statements to a

database. 

Copyright © 2008, Infosys Technologies Ltd. Confidential1616

Statement interface Statement interface

Defines methods that are used to interact with database via the execution of SQL statements.

The different methods are: executeQuery(String sql) - executes an SQL statement (SELECT) that

queries a database and returns a ResultSet object.

executeUpdate(String sql) - executes an SQL statement (INSERT,UPDATE,or DELETE) that updates the database and returns an int, the row count associated with the SQL statement

Copyright © 2008, Infosys Technologies Ltd. Confidential1717

ResultSet InterfaceResultSet Interface

Maintains a pointer to a row within the tabular results.

The next() method is used to successively step through the rows of the tabular results. It is initialized to a position before the first row. We must call next() once to move it to the first row.

The different methods are: getBoolean(int) - Get the value of a column in the current row as a Java

boolean. getByte(int) - Get the value of a column in the current row as a Java byte. getDouble(int) - Get the value of a column in the current row as a Java

double. getInt(int) - Get the value of a column in the current row as a Java int.

Copyright © 2008, Infosys Technologies Ltd. Confidential1818

Using Statement and ResultSet Using Statement and ResultSet

StatementDemo.java

Copyright © 2008, Infosys Technologies Ltd. Confidential1919

Creating a PreparedStatement object Creating a PreparedStatement object

Helps us to work with precompiled SQL statements

Precompiled SQL statements are faster than normal statements

So, if a SQL statement is to be repeated, it is better to use PreparedStatement

To execute SQL statements, we need to instantiate a PreparedStatement object from the connection object by using the prepareStatement () method.

PreparedStatement preparedStatement = connection.prepareStatement("select * from student where sid=?");

Some values of the statement can be represented by a ? character which can be replaced later using setXXX () method

Copyright © 2008, Infosys Technologies Ltd. Confidential2020

PreparedStatement DemoPreparedStatement Demo

PreparedStatementDemo.java

Copyright © 2008, Infosys Technologies Ltd. Confidential2222

ResultSetMetaData Interface ResultSetMetaData Interface

Holds information on the types and properties of the columns in a ResultSet.

Provides information about the database as a whole. Constructed from the Connection object

Some of the methods are: String getColumnName(int column) String getColumnTypeName(int column) int getColumnCount();

ResultSetMetaDemo.java

Copyright © 2008, Infosys Technologies Ltd. Confidential2323

Transaction Management using JDBC Transaction Management using JDBC

By default, auto commit mode of the connection reference is set to true

A transaction can be done as follows using methods of the Connection interface

...connection.setAutoCommit(false); //by default it is truetry{

//Statementsconnection.commit();

}catch(Exception exception){

connection.rollback();}

Copyright © 2008, Infosys Technologies Ltd. Confidential2424

Can you answer the following ? Can you answer the following ?

Why JDBC ?How to Set up a connection to a database from Java using

JDBC?What are the different methods provided by statement

interface?Why do you prefer preparedstatement over statement

interface?

Copyright © 2008, Infosys Technologies Ltd. Confidential2525

Summary Summary

Java Data Base Connectivity JDBC API Different drivers Set up a connection to a database from Java Create a database application

Copyright © 2008, Infosys Technologies Ltd. Confidential

Introduction to JPAIntroduction to JPA

ER/CORP/CRS/ED111/003ER/CORP/CRS/ED111/003 Ver. No.: 1.0Ver. No.: 1.0 Copyright © 2008, Infosys Technologies Ltd.Copyright © 2008, Infosys Technologies Ltd.

Education and Research We enable you to leverage knowledge anytime, anywhere!

Confidential

Copyright © 2008, Infosys Technologies Ltd. Confidential

Data Persistence Data Persistence

Data persistence is one of the most critical operations for Enterprise Applications.

Persistent data normally refers to permanent data in an application.

The state of these data is made permanent by storing them in a persistent medium like database, files or a disk tape.

2727

Copyright © 2008, Infosys Technologies Ltd. Confidential

Java Persistence API (JPA)Java Persistence API (JPA)

JPA provides API for persistence Object/Relational(O/R) metadata(Annotation) Java Persistence Query Language(JPQL)

Persistence deals with storing and retrieving of application data

It is done with the help of Entity(Java Object)

2828

Copyright © 2008, Infosys Technologies Ltd. Confidential

ORM ExampleORM Example

2929

Customer

- customerID - int- name - String

Customer

customerID:int(8)Name:varchar2(20)

Employee

- EmployeeId-int- Name-String

Employee

EmployeeID:int(8)Name:varchar2(10)

Account

- AccountId- int

Saving Account

Current Account

Account

AccountID:int(8) ………

Account

-TransactionID - int

-AccountId- int- Type -String

Transaction

TransactionID : int(8……….

*

Transaction

Copyright © 2008, Infosys Technologies Ltd. Confidential

Entity Entity

An Entity refers to a logical collection of data that can be stored or retrieved as a whole. Entity is a java object.

For example, in a banking application, Account can be an Entity.

accountNumber, balance etc are properties/attributes of Account Entity.

Identity property is used to identify one unique entity among multiple entities (or multiple entity instances) in a database. In Account Entity accountNumber acts as an Identity property.

3030

Copyright © 2008, Infosys Technologies Ltd. Confidential

Creating an EntityCreating an Entity

A persistable class must be annotated or prefixed with javax.persistence.Entity annotation.

The instance of the class will represent one row in the table.

By default, the table name corresponds to the class name. Each property should have getter and setter method. The class should contain default or no-argument

constructor

3131

Copyright © 2008, Infosys Technologies Ltd. Confidential

Employee BeanEmployee Bean

3232

public class Employee {private int empId;private String name;public Employee() {}public Employee(int empId) {

this. empId = empId; }public int getEmpId() {

return empId; }public void setEmpId(int empId) {

this. empId = empId; }public String getName() {

return name; }public void setName(String name) {

this.name = name; }}

Copyright © 2008, Infosys Technologies Ltd. Confidential

Employee Entity Employee Entity

3333

empId(PK) name

101 John

102 Jack

103 Joe

@Entity // To make Employee as an Entitypublic class Employee {

@Id // To make empId as primary keyprivate int empId;private String name;public Employee() {}public Employee(int empId) {

this. empId = empId; }public int getEmpId() {

return empId; }public void setEmpId(int empId) {

this. empId = empId; }public String getName() {

return name; }public void setName(String name) {

this.name = name; }}

Employee Table

Copyright © 2008, Infosys Technologies Ltd. Confidential

Mapping to a TableMapping to a Table

@Entity and @Id annotations need to be specified to map an entity to a database table.

By default, table name will be the name of the entity class without the package name.

@Table annotation will be used to specify the name of the table if the names are different.

Overriding the default table name

@Entity

@Table(name="EMP")

public class Employee { ... }

3434

empId(PK) name

101 John

102 Jack

103 Joe

EMP Table

Copyright © 2008, Infosys Technologies Ltd. Confidential

Column MappingsColumn Mappings

3535

EMP_ID EMP_NAME

101 John

102 Jack

103 Joe

Employee Table@Entitypublic class Employee { @Id @Column(name="EMP_ID") private int id;

@Column(name=“EMP_NAME") private String name;

// ...getter and setter methods

}

@Column annotation will be used to specify the name of the column

if entity property name is different from column name in the table

Copyright © 2008, Infosys Technologies Ltd. Confidential

Temporal TypesTemporal Types

Temporal types are the set of time-based types To persist Temporal data types of java, @Temporal

annotation is used The list of supported temporal types used in Entity

– java.util.Date and java.util.Calendar

3636

Copyright © 2008, Infosys Technologies Ltd. Confidential

Mapping Temporal TypesMapping Temporal Types

3737

In Entity Mapped To Database

TemporalType.DATE Mapped to java.sql.Date

TemporalType.TIME Mapped to java.sql.Time

TemporalType.TIMESTAMP Mapped to java.sql.Timestamp

Different Temporal Types from JPA

@Entitypublic class Employee { @Id private int id;

@Temporal(TemporalType.DATE) private Calendar dob;

@Temporal(TemporalType.TIME) private Date startDate; // ...}

Project.java

Copyright © 2008, Infosys Technologies Ltd. Confidential

Transient StateTransient State

Attributes that are part of an entity but not required to be persisted should be prefixed with the @Transient annotation

3838

@Entitypublic class Employee { @Id private int empid; private String name; private long salary; @Transient private String translatedName; // getter and setter method}

Employee Table

empid name salary

100 John 1000

101 Jack 2000

translatedName will not be persisted

Copyright © 2008, Infosys Technologies Ltd. Confidential

Persisting an Entity Using JPAPersisting an Entity Using JPA

Steps involved in persisting an Entity are Configuring persistence unit in persistence.xml Creating an instance of EntityManagerFactory Obtaining instance of EntityManager Persist the Entity

– Begin EntityTransaction

– Invoke persist() method

– Commit the Transaction

Next

3939

Copyright © 2008, Infosys Technologies Ltd. Confidential

EntityManagerFactoryEntityManagerFactory

It is used to create an instance of EntityManager

EntityManagerFactory emf = Persistence.

createEntityManagerFactory("EmployeeService");

Obtaining an EntityManager from an EntityManagerFactory

reference

EntityManager em = emf.createEntityManager();

Back

4040

Persistent Unit name.

Copyright © 2008, Infosys Technologies Ltd. Confidential

EntityManager EntityManager

Provides API for interacting with the Entity

Some of the functions provided by EntityManager API are: persist() – save a new entity to the database table remove() –remove the entity from the database table find() – Get the existing entity from the database table

Back4141

Copyright © 2008, Infosys Technologies Ltd. Confidential

Persistence UnitPersistence Unit

A persistent unit is a collection of entities that are managed together.

It specifies the persistent provider name, entity class names, and properties like the database connection URL, driver, user and password etc.

Persistence Unit is defined inside persistence.xml file. Each persistence unit has a name. EntityManagerFactory needs the name of the persistence unit to

persist an entity

Back4242

Copyright © 2008, Infosys Technologies Ltd. Confidential

persistence.xmlpersistence.xml<?xml version="1.0" encoding="UTF-8"?>

<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">

<persistence-unit name=" EmployeeService " transaction-type="RESOURCE_LOCAL">

<provider>oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider</provider>

<class>com.infy.Employee</class>

<properties>

<property name="toplink.jdbc.url" value=“ jdbc:oracle:thin: @10.122.130.40:1521/georli01"/>

<property name="toplink.jdbc.user" value="er106657"/>

<property name="toplink.jdbc.driver" value="oracle.jdbc.driver.OracleDriver"/>

<property name="toplink.jdbc.password" value="infy"/>

<property name="toplink.ddl-generation" value="create-tables"/>

</properties>

</persistence-unit>

</persistence> Click here to know more on Persistence Unit4343

Copyright © 2008, Infosys Technologies Ltd. Confidential

Persisting an Entity (1 of 2)Persisting an Entity (1 of 2)

Persisting an entity is saving its state so that it can be retrieved later. EntityManagerFactory emf = Persistence. createEntityManagerFactory("EmployeeService");

EntityManager em = emf.createEntityManager();

EntityTransaction et=em.getTransaction();

et.begin();

Employee employee = new Employee();

employee.setEmpId(158);

employee.setName(“Ritchie”);

em.persist(employee);

if(et!=null) {

et.commit();}

Entities must be persisted using a Transaction.

4444

Copyright © 2008, Infosys Technologies Ltd. Confidential

Persisting an Entity (2 of 2)Persisting an Entity (2 of 2)

4545

package com.infy

@Entity

public class Employee{

@Id

int empId;

String name;

//getter and setter

}

<persistence-unit name=" EmployeeService " transaction-type="RESOURCE_LOCAL"><provider>oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider</provider> <class> </class><properties> <property name="toplink.jdbc.url . . . .

. . . . . . .value="create-tables"/> </properties> </persistence-unit>

EntityManagerFactory emf = Persistence.createEntityManagerFactory(“ ");EntityManager em = emf.createEntityManager();EntityTransaction et=em.getTransaction();et.begin();Employee emp1= new Employee();emp1.setEmpID(158);emp1.setName(“Ritchie”);em.persist(emp1);et.commit();

EmployeeService

com.infy

.Employee

EMPID NAME

158 Ritchie

Copyright © 2008, Infosys Technologies Ltd. Confidential

Finding an EntityFinding an Entity

An entity can be retrieved using the EntityManager

Employee employee = em.find(Employee.class, 158);

The first argument is Entity class

The second argument is the id or primary key that identifies the particular entity

If that record does not exist in the table, find() returns null.

4646

Copyright © 2008, Infosys Technologies Ltd. Confidential

Updating an EntityUpdating an Entity

In order to update an entity, the entity must be present in the persistence context.

EntityTransaction et=em.getTransaction();

et.begin();

Employee emp = em.find(Employee.class, 158);

if (emp != null) {

emp.setSalary(emp.getSalary() + 1000);

}

et.commit();

4747

Copyright © 2008, Infosys Technologies Ltd. Confidential

Removing an EntityRemoving an Entity

Similar to DELETE operation in the database In order to remove an entity, the entity must be present in the

persistence context A simple example for removing a row from employee table is: EntityTransaction et=em.getTransaction();

et.begin();

Employee emp = em.find(Employee.class, 158);

if (emp != null) {

em.remove(emp);

}

et.commit();

4848

Copyright © 2008, Infosys Technologies Ltd. Confidential

DemosDemos

4949

persistence.xmlEmployees.Java Employee

Persistence

Finding an Entity Instance Updaing Employee

InstanceRemoving Employee

Instance

Copyright © 2008, Infosys Technologies Ltd. Confidential

Entity Life CycleEntity Life Cycle

5050

Does not existDoes not exist

newnew

removedremoved

managedmanaged

detacheddetached

Object ConstructionObject obj=new Object();

1. EntityManager.remove(obj)2. @PreRemove3. Pending removal in database

1. EntityManager.persist (obj)2. @PrePersist3. Database insert4. @PostPersist

Transaction Ends

1. Update Query2. @Pre Update3. Database Update4. @Post Update

Copyright © 2008, Infosys Technologies Ltd. Confidential

Life cycle callback MethodsLife cycle callback Methods

Callback methods are called automatically by the application when a particular condition is met.

It is often necessary to perform various actions at different stages of a persistent object's lifecycle.

JPA includes a variety of callback methods.

These methods will be called automatically by the application for life cycle events of an entity

They can be defined on the persistent classes themselves or on non-persistent listener classes.

5151

Copyright © 2008, Infosys Technologies Ltd. Confidential

Annotations for call back methodsAnnotations for call back methods

5252

Annotation Description

@PrePersist Invoked for an entity before persist operation is executed.

@PostPersist Invoked for an entity after persist operation is executed

@PreRemove Invoked for an entity before remove operation is executed

@PostRemove Invoked for an entity after remove operation is executed.

@PreUpdate Invoked for an entity before update operation is executed

@PostUpdate Invoked for an entity after update operation is executed

Call back methods should be prefixed by any one of the following annotation

Copyright © 2008, Infosys Technologies Ltd. Confidential

Call back methods inside EntityCall back methods inside Entity

Any method may be used which takes no arguments Multiple annotation can be assigned to a single

method. Same life cycle annotation cannot be given to many

methods

5353

Copyright © 2008, Infosys Technologies Ltd. Confidential

ExampleExample

5454

@Entitypublic class Employee { @Id private int empId; ....

public Employee() {} public int getEmpId(){ return empId; } public void setEmpId(int empId){ this. empId = empId; } .... @PrePersist public void initialize() { System.out.println("Trying to insert"); }}

The initialize method will be called automatically before persisting the Entity. The method name may be anything but it should be prefixed with @PrePersist

Copyright © 2008, Infosys Technologies Ltd. Confidential

Using Entity Listeners Using Entity Listeners

Mixing lifecycle event code into persistent classes is not a good practice.

It is better to handle lifecycle events in a non-persistent listener class (a simple java class).

Listener classes must have a public no-argument constructor

Listener classes can implement any number of callbacks

The callback methods must take single argument of type java.lang.Object or Entity

5555

Copyright © 2008, Infosys Technologies Ltd. Confidential

ExampleExample

5656

Entity@Entity@EntityListeners( EmployeeListener.class)public class Employee { @Id private int id; .... ....

public Employee() {} public int getId() {return id;} public void setId(int id) { this.id = id; } .... }

Listener

public class EmployeeListener {

@PrePersist public void initialize(Employee e) { System.out.println("Trying to

insert"); }}

Project.java

ProjectEntityListener.javaProjectService.java

Copyright © 2008, Infosys Technologies Ltd. Confidential

Can you answer these questions?Can you answer these questions?

What are the following annotations used for @Id @Table @Transient @Temporal

What are the steps involved in persisting an Entity? What are the different attributes of Persistence Unit? What are the various ways of implementing lifecycle

callback methods?

5757

Copyright © 2008, Infosys Technologies Ltd. Confidential5858

Thank You

“The contents of this document are proprietary and confidential to Infosys Technologies Ltd. and may not be disclosed in whole or in part at any time, to any third party without the prior written consent of Infosys Technologies Ltd.”

“© 2008 Infosys Technologies Ltd. All rights reserved. Copyright in the whole and any part of this document belongs to Infosys Technologies Ltd. This work may not be used, sold, transferred, adapted, abridged, copied or reproduced in whole or in part, in any manner or form, or in any media, without the prior written consent of Infosys Technologies Ltd.”

Copyright © 2008, Infosys Technologies Ltd. Confidential

AppendixAppendix

ER/CORP/CRS/ED111/003ER/CORP/CRS/ED111/003 Ver. No.: 1.0Ver. No.: 1.0 Copyright © 2008, Infosys Technologies Ltd.Copyright © 2008, Infosys Technologies Ltd.

Education and Research We enable you to leverage knowledge anytime, anywhere!

Confidential

Copyright © 2008, Infosys Technologies Ltd. Confidential6060

CallableStatement (1 of 3)CallableStatement (1 of 3)

Helps us to call stored procedures and functions

To call a procedure/function, we need to instantiate a CallableStatement object from the connection object by using the prepareCall () method.

CallableStatement callableStatement = connection. prepareCall ("{call GetSalary(?,?)}");

Some values of the statement can be represented by a ? character which can be replaced later using setXXX () method. This is used for input (in) parameters

Copyright © 2008, Infosys Technologies Ltd. Confidential6161

CallableStatement (2 of 3)CallableStatement (2 of 3)

The out parameters are to be registered

callableStatement.registerOutParameter(int parameterIndex, int SQLType);

To get the value stored in the out parameter--

callableStatement.getXXX(int parameterIndex);

Copyright © 2008, Infosys Technologies Ltd. Confidential

CallableStatement (3 of 3)CallableStatement (3 of 3)

6262

Employee.java

CallableStatementDemo.java

DemoTable & SP.txt