Sunteți pe pagina 1din 33

Java Stored Procedures

Oracle Day 4

Objectives
Integration of Java and Oracle

PL/SQL vs. Java Stored Procedures


Understanding Java Stored Procedures

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/DB25/003 Version No. 2.0

What is Java?
Java is an object-oriented programming language developed by Sun Microsystems.

Modeled after C++, the Java language was designed to be:


Small Simple Portable across platforms

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/DB25/003 Version No. 2.0

What is a Stored Procedure ?


A set of Structured Query Language (SQL) statements

Stored in a database in compiled form so that one can share it between a number of programs

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/DB25/003 Version No. 2.0

What is a Java Stored Procedure ?


Java methods stored in the database.

An open and portable alternative to proprietary procedural SQL extensions (PL/SQL), for implementing stored procedures.

Java stored procedures are Java classes, stored as Oracle schema objects, made accessible to Oracle SQL and PL/SQL through call specifications.

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/DB25/003 Version No. 2.0

Integration of Oracle and Java


Oracles Java Virtual Machine - Aurora

Since Oracle8i, the Oracle database embeds a Java VM, which lets run Java directly in the database

The latest Oracle 10g server is compliant with J2SE (Java 2 Server Edition) 1.4x

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/DB25/003 Version No. 2.0

How does it work?


Thin Client(s)

Java Applet

JDBC Driver
le ac Or Ne

Oracle Database

Fat Client(s)

Relational Data

Object Relational Data

SQL * Plus

PRO * Client

ODBC Client

Oracle Net

Oracle Net Oracle Net Connection Manager

Data for Java PL/SQL cover Method

O ra cle

Ne

Aurora running Java Method

PL/SQL stored Procedure

Oracle Forms

Oracle Reports

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/DB25/003 Version No. 2.0

PL/SQL vs. Java Stored Procedures


Whether to use PL/SQL or Java stored procedures is the legitimate million dollar question.

Should I forget all the things I've been told about PL/SQL and move on to the greener Java pastures?

Lets cut to the chase..

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/DB25/003 Version No. 2.0

PL/SQL Stored Procedures


PL/SQL is Oracles procedural extension to SQL.

PL/SQL is designed and optimized for stored procedures and functions.

Well suited for encapsulating SQL operations with procedural logic and for manipulating all database object types.

Extensively used by a large community of Oracle developers and customers for implementing database operations and packages.

Copyright 2005, Infosys Technologies Ltd

ER/CORP/CRS/DB25/003 Version No. 2.0

Java Stored Procedures 1/2


Represent an open, database-independent (They can be written outside the database) alternative to PL/SQL and bring:

Robustness
As opposed to PL/SQL, Java requires declaring exceptions that can be thrown by methods in any class, thereby making Java stored procedures more robust.

Reuse of Java skills


Java is one of the dominant programming languages, it is likely that Java programmers already exist within ones company.

Cross-Vendor and Cross-Platform Portability


All major databases vendors provide Java support in their database, either through a tight integration with the database runtime such as Oracle or through a loosely coupled integration. Java stored procedures not only inherit cross-platform portability from the database but, moreover, cross-vendor portabilityin other words, database independence.

Copyright 2005, Infosys Technologies Ltd

10

ER/CORP/CRS/DB25/003 Version No. 2.0

Java Stored Procedures- 2/2


Complex database logic and powerful usage patterns
Java programming in the database allows implementing more complex database logic than PL/SQL and extends database functionality.

Power, richness, and object-orientation of the Java language

Copyright 2005, Infosys Technologies Ltd

11

ER/CORP/CRS/DB25/003 Version No. 2.0

Java Stored Proc vs. PL/SQL - General Rule of Thumb


Use PL/SQL for database-centric logic that requires seamless integration with SQL and therefore complete access to database objects, types, and features.

Use Java as an open alternative to PL/SQL for database independence, and for integrating and bridging the worlds of SQL, XML, J2EE, and Web services.

Copyright 2005, Infosys Technologies Ltd

12

ER/CORP/CRS/DB25/003 Version No. 2.0

Steps to create a Java Stored Procedure


Create the Java code element Load the Java classes into Oracle-LOADJAVA utility Publish the Java class methods-WRAPPER program Grant privileges Calling the Java Stored Procedure

Let us understand with an example

Copyright 2005, Infosys Technologies Ltd

13

ER/CORP/CRS/DB25/003 Version No. 2.0

Create the Java code element STEP 1/5


We will use a simple Hello class, with one method, helloWorld(), that returns the string "Hello world":
Why Public and Static?

// Hello World Program public class Hello{ public static String helloWorld(){

return "hello world";


} }

Compile the program to generate the java class file.


Copyright 2005, Infosys Technologies Ltd ER/CORP/CRS/DB25/003 Version No. 2.0

14

Load the Java class into Oracle-LOADJAVA utility STEP 2/5 Utility for loading Java source files, Java class files, and Java resource files
Invoked from the command line loadjava u username/password@oracleSID -r v <classfile> For our Hello class run the following command from the command line:

loadjava -u scott/tiger@training -r -v Hello.class

Copyright 2005, Infosys Technologies Ltd

15

ER/CORP/CRS/DB25/003 Version No. 2.0

First time - run LOADJAVA utility.


The first time one run LOADJAVA in a schema, it creates following elements for its own use:

CREATE$JAVA$LOB$TABLE
JAVA$CLASS$MD5$TABLE LOADLOBS

Copyright 2005, Infosys Technologies Ltd

16

ER/CORP/CRS/DB25/003 Version No. 2.0

Imp options - LOADJAVA utility.


-verbose | v

-resolve | r

-force | f

Copyright 2005, Infosys Technologies Ltd

17

ER/CORP/CRS/DB25/003 Version No. 2.0

Examining Loaded Java Elements in Oracle


USER_OBJECTS data dictionary view is used to check the loaded Java elements in Oracle Following query is used to figure out the loaded Java elements in Oracle: COLUMN object_name FORMAT A30 SELECT object_name, object_type, status, timestamp FROM user_objects WHERE (object_name NOT LIKE 'SYS_%' AND object_name NOT LIKE 'CREATE$%' AND object_name NOT LIKE 'JAVA$%' AND object_name NOT LIKE 'LOADLOB%')

AND object_type LIKE 'JAVA%'


ORDER BY object_type, object_name

Copyright 2005, Infosys Technologies Ltd

18

ER/CORP/CRS/DB25/003 Version No. 2.0

DROPJAVA utility
Reverses the action of loadjava

Converts filename into the name of schema objects, drops the schema objects, and finally deletes their digest table rows.

Syntax: dropjava u username/password@OralceSID filename

To drop Hello class from Oracle execute the following command from command line: dropjava u scott/tiger@training Hello.class
Copyright 2005, Infosys Technologies Ltd ER/CORP/CRS/DB25/003 Version No. 2.0

19

Publish the Java class methods- STEP 3/5


PL/SQL WRAPPER program are required to publish the Java Methods.

Following PL/SQL wrapper program is required to publish the Java method helloWorld:

SQL>CREATE OR REPLACE FUNCTION proc_get_msg

RETURN VARCHAR2
AS LANGUAGE JAVA NAME 'Hello.helloWorld() return java.lang.String';

Copyright 2005, Infosys Technologies Ltd

20

ER/CORP/CRS/DB25/003 Version No. 2.0

Rules for PL/SQL Wrappers


A PL/SQL wrapper and the Java method it publishes must reside in the same schema.

One can publish only public static Java methods.


Default values are not allowed in the parameter list of the PL/SQL wrapper. One have to take care of mapping datatypes between Java methods and PL/SQL wrapper.

Copyright 2005, Infosys Technologies Ltd

21

ER/CORP/CRS/DB25/003 Version No. 2.0

Grant privileges STEP 4/5

. Optional Step

To allow Java related operation Oracle allow following roles:

JAVAUSERPRIV: To read or write a file, one only need the JAVAUSERPRIV role.

JAVASYSPRIV: To create a file through Java, one need JAVASYSPRIV role.

DBA has to Issue the following command to execute the grant:

SQL>GRANT JAVAUSERPRIV TO username

Copyright 2005, Infosys Technologies Ltd

22

ER/CORP/CRS/DB25/003 Version No. 2.0

Calling the Java Stored Procedure STEP 5/5


The final step of our example:

Define the variable to get the message returned by function SQL> VARIABLE var_msg VARCHAR2(20);

Call the Function (get the return value into the variable)

SQL> CALL proc_get_msg() INTO :var_msg;

Print the result SQL> PRINT var_msg;

Copyright 2005, Infosys Technologies Ltd

23

ER/CORP/CRS/DB25/003 Version No. 2.0

Calling the Java Stored Procedure ..


Java Stored Procedures can be called from:

SQL DML statements (INSERT, UPDATE, DELETE, SELECT, CALL, EXPLAIN PLAN, LOCK TABLE, and MERGE )

PL/SQL blocks, subprograms, and packages

Database triggers

Copyright 2005, Infosys Technologies Ltd

24

ER/CORP/CRS/DB25/003 Version No. 2.0

Rules for calling Java Stored Procedure - Purity Rules


If one calls a method from SELECT statement , he is not allowed to modify any database tables.

If one calls a method from an INSERT, UPDATE, or DELETE statement, the method cannot query or modify any database tables modified by that statement.
If one calls a method from a SELECT, INSERT, UPDATE, or DELETE statement, the method cannot execute: SQL transaction control statements e.g. COMMIT SQL session control statements e.g. SET ROLE DDL statements.

Copyright 2005, Infosys Technologies Ltd

25

ER/CORP/CRS/DB25/003 Version No. 2.0

A working Java Stored Procedure example Learn More!


This sample Java stored procedure is going to insert a record in the employee table.

The relation employee is defined as:

employee (emp_id, emp_f_name, emp_l_name, emp_salary,dept_id)

Copyright 2005, Infosys Technologies Ltd

26

ER/CORP/CRS/DB25/003 Version No. 2.0

Create the Java code element


import java.sql.*; import oracle.jdbc.*;
public class EmpManager { //Add an employee to the database. public static void addEmp(int emp_id, String emp_f_name, String emp_l_name, float emp_salary, int dept_id) { System.out.println("Creating new employee..."); try { Connection conn = DriverManager.getConnection("jdbc:default:connection:"); String sql = "INSERT INTO employee " + "(emp_id,emp_f_name,emp_l_name,emp_salary,dept_id) " + "VALUES(?,?,?,?,?)"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setInt(1,emp_id); pstmt.setString(2,emp_f_name); pstmt.setString(3,emp_l_name); pstmt.setFloat(4,emp_salary); pstmt.setInt(5,dept_id); pstmt.executeUpdate(); pstmt.close(); } catch(SQLException e) { System.err.println("ERROR! Adding Employee: " + e.getMessage()); } } }

Copyright 2005, Infosys Technologies Ltd

27

ER/CORP/CRS/DB25/003 Version No. 2.0

Loading the Java class


loadjava -u scott/tiger@training -v -r EmpManager.class

Copyright 2005, Infosys Technologies Ltd

28

ER/CORP/CRS/DB25/003 Version No. 2.0

Publishing java class methods


CREATE OR REPLACE PROCEDURE add_emp (emp_id NUMBER, emp_f_name VARCHAR2, emp_l_name VARCHAR2, emp_salary NUMBER, dept_id NUMBER) AS LANGUAGE JAVA NAME EmpManager.addEmp(int, java.lang.String, java.lang.String,float, int)';

Copyright 2005, Infosys Technologies Ltd

29

ER/CORP/CRS/DB25/003 Version No. 2.0

Calling Java stored procedure


SQL> SET SERVEROUTPUT ON SQL> CALL dbms_java.set_output(2000); SQL> EXECUTE add_emp(1,Anubhav', Pradhan',50000.00,1);

Copyright 2005, Infosys Technologies Ltd

30

ER/CORP/CRS/DB25/003 Version No. 2.0

Conclusion
The integration of the database with a JVM that complies with J2SE allows extending database features and programmability through Java Stored Procedures.

Copyright 2005, Infosys Technologies Ltd

31

ER/CORP/CRS/DB25/003 Version No. 2.0

Summary
What is Java Stored Procedure? PL/SQL vs. Java Stored Procedures. What are the steps to create a Java Stored Procedure? How to load Java code elements? What are Call specs.? How to call Java Stored Procedures?

Copyright 2005, Infosys Technologies Ltd

32

ER/CORP/CRS/DB25/003 Version No. 2.0

Thank You!
Copyright 2005, Infosys Technologies Ltd
33

ER/CORP/CRS/DB25/003 Version No. 2.0

S-ar putea să vă placă și