8/8/2019 Java Stored
1/118
Oracle8i
Java Stored Procedures Developers Guide
Release 8.1.5
February 1999
Part No. A64686-01
8/8/2019 Java Stored
2/118
Java Stored Procedures Developer s Guide, Release 8.1.5
Part No. A64686-01
Copyr ight 1999, Oracle Corporation . All rights reserved.
Author: Tom Portfolio
Graphics Artist: Valarie Moore
Contributors: Dave Alpern, Gray Clossman, Matthieu Devin, Steve Harris, Hal Hildebrand,Thomas Kur ian, Dave Rosenberg, Jerry Schwarz
The Programs are not intended for use in any nuclear, aviation, mass transit, medical, or otherinherently dangerous applications. It shall be the license es responsibility to take all appropriatefail-safe, backup, redundancy and other measures to ensure the safe use of such applications if thePrograms are used for such purposes, and Oracle disclaims liabil ity for any damages caused by suchuse of the Programs.
The Programs (which include both the software and d ocumentation) contain proprietary information ofOracle Corporation; they are provided u nd er a license agreement containing restrictions on u se anddisclosure and are also protected by copyright, patent, and oth er intellectual and indu strial propertylaws. Reverse engineering, disassembly, or d ecompilation of the Program s is proh ibited.
The information contained in this document is subject to change without notice. If you find any problemsin the documen tation, please report them to us in writing. Oracle Corporation does not warr ant that thisdocum ent is error free. Except as may be expressly perm itted in your license agreement for thesePrograms, no part of these Programs may be reproduced or transmitted in any form or by any means,electronic or mechanical, for any p urp ose, without the express wr itten perm ission of Oracle Corpor ation.
If the Programs are d elivered to the U.S. Governmen t or anyon e licensing or u sing the Program s onbehalf of the U.S. Government, the following notice is applicable:
Restricted Rights Notice Program s delivered su bject to the DOD FAR Supplemen t are "commercial
computer software" and use, duplication, and disclosure of the Programs including documentation, shallbe subject to the licensing restrictions set forth in the app licable Oracle license agreement. Oth erwise,Program s d elivered su bject to the Federal Acquisition Regulations are "restricted compu ter software"and use, duplication, and disclosure of the Programs shall be subject to the restrictions in FAR 52.227-19,Commercial Computer Software - Restricted Rights (June, 1987). Oracle Corporation, 500 OracleParkwa y, Redw ood City, CA 94065.
Oracle, Oracle Call Interface, Oracle Forms, Oracle Reports, and SQL*Plus are registered trademarks ofOracle Corporation. JDeveloper, JPublisher, Net8, Oracle8i, PL/ SQL, and Pro*C/ C++ are trademarks ofOracle Corporation.All other company or product names mentioned are used for identification purposesonly and m ay be trademar ks of their respective owners.
8/8/2019 Java Stored
3/118
i
Contents
Send Us Your Comments .................................................................................................................... v
Preface........................................................................................................................................................... vii
1 IntroductionJava in the RDBMS: A Robust Combination ................................................................................ 1-2
Stored Procedures and Run-Time Contexts................................................................................... 1-3
Funct ions an d Proced ures ........................................................................................................... 1-4
Database Triggers ......................................................................................................................... 1-4
Object-Relational Method s .......................................................................................................... 1-5
Advantages of Stored Procedures .................................................................................................... 1-6
Performance................................................................................................................................... 1-6
Prod uctivity and Ease of Use ...................................................................................................... 1-6
Scalability ....................................................................................................................................... 1-7
Mainta inability .............................................................................................................................. 1-7
Interoperability ............................................................................................................................. 1-7
Security........................................................................................................................................... 1-7
Rep lication ..................................................................................................................................... 1-8The Aurora JVM and Its Components ............................................................................................ 1-9
The Au rora JVM versus Clien t JVMs....................................................................................... 1-10
Main Com ponents of the Au rora JVM .................................................................................... 1-11
Developing Stored Procedures: An Overview ............................................................................ 1-15
Write or Reuse the Proced ures ................................................................................................. 1-15
Load the Procedures in to the RDBMS..................................................................................... 1-15
http://comments_template.pdf/http://comments_template.pdf/8/8/2019 Java Stored
4/118
ii
Publish the Procedures in the Oracle Data Dictionary.......................................................... 1-15
Call the Proced ures from SQL and PL/ SQL........................................................................... 1-15
2 Loading Stored Procedures
Java in the Database ........................................................................................................................... 2-2
Managing Java Schema Objects ....................................................................................................... 2-4
Wh at to Load ................................................................................................................................. 2-4
How Externa l References Are Resolved .................................................................................... 2-4What the Digest Table Does ........................................................................................................ 2-7
How Com pilat ion Is Done ........................................................................................................... 2-8
Using loadjava ................................................................................................................................... 2-10
Specifying the User ..................................................................................................................... 2-13
Specifying Filenames.................................................................................................................. 2-13
Exam ples ...................................................................................................................................... 2-15
Reload ing Files ............................................................................................................................ 2-15Checkin g Up load Resu lts .......................................................................................................... 2-16
Using dropjava .................................................................................................................................. 2-19
Specifying Filenames.................................................................................................................. 2-20
Exam ples ...................................................................................................................................... 2-20
Invoker Rights versus Definer Rights........................................................................................... 2-21
3 Publishing Stored Procedures
Understanding Call Specs ................................................................................................................. 3-2
Defining Call Specs: Basic Requirements ...................................................................................... 3-3
Settin g Parameter Modes............................................................................................................. 3-3
Mapping Datatypes ...................................................................................................................... 3-4
Usin g the Server-Side JDBC Driver............................................................................................ 3-6
Usin g the Server-Side SQLJ Translator ...................................................................................... 3-8Writing Top-Level Call Specs ......................................................................................................... 3-10
Example 1..................................................................................................................................... 3-11
Example 2..................................................................................................................................... 3-12
Example 3..................................................................................................................................... 3-12
Example 4..................................................................................................................................... 3-13
8/8/2019 Java Stored
5/118
iii
Writing Packaged Call Specs .......................................................................................................... 3-14
An Example ................................................................................................................................. 3-15Writing Object Type Call Specs ..................................................................................................... 3-17
Declaring At tr ibutes ................................................................................................................... 3-18
Declaring Meth od s ..................................................................................................................... 3-18
Examples ...................................................................................................................................... 3-20
4 Calling Stored Procedures
Calling Java from the Top Level ...................................................................................................... 4-2
Redirecting Output....................................................................................................................... 4-2
Example 1....................................................................................................................................... 4-3
Example 2....................................................................................................................................... 4-4
Calling Java from Database Triggers .............................................................................................. 4-6
Example 1....................................................................................................................................... 4-6
Example 2...................................................................................................................................... 4-8Calling Java from SQL DML ......................................................................................................... 4-10
Restrictions .................................................................................................................................. 4-11
Calling Java from PL/SQL............................................................................................................... 4-12
Calling PL/SQL from Java ............................................................................................................... 4-14
How Exceptions Are Handled ........................................................................................................ 4-15
5 Developing an Application
Drawing the Entity-Relationship Diagram ................................................................................... 5-2
Planning the Database Schema........................................................................................................ 5-5
Creating the D atabase Tables ........................................................................................................... 5-7
Writing the Java Stored Procedures ................................................................................................. 5-9
Loading the Java Stored Procedures ............................................................................................. 5-13
Publishing the Java Stored Procedures ........................................................................................ 5-14Calling the Java Stored Procedures ............................................................................................... 5-16
Index
8/8/2019 Java Stored
6/118
iv
8/8/2019 Java Stored
7/118
v
Send Us Your Comments
Oracle8iJava Stored Procedures Developers Guide, Release 8.1.5
Part No. A64686-01
Oracle Corpora tion welcomes your comm ents and suggestions on the qua lity and usefulness of this
pu blication. Your inp ut is an imp ortant p art of the information used for revision.
s Did you find any errors?
s Is the information clearly presented?
s Do you n eed m ore information? If so, where?
s Are the examp les correct? Do you need more examp les?
s What features did you like most about this manu al?
If you find any errors or have any other suggestions for improvemen t, please indicate the chap ter,
section, and p age nu mber (if available). You can send comments to the following email ad dress:[email protected]
If you w ould like a reply, please give your nam e, address, and telephon e num ber below.
If you h ave p roblems with the software, please contact your local Oracle World Wide Sup port Center.
8/8/2019 Java Stored
8/118
vi
8/8/2019 Java Stored
9/118
vii
Preface
Welcome to th e future of da tabase program ming. The rap id rise of Java has forever
changed th e art of software developm ent. Now, using intran ets, the Internet, and
Java's cross-platform ability, you can develop applications with global reach. The
Oracle8i da tabase server and its Java Virtual Machine (JVM) provid e an ideal
platform on w hich to dep loy such applications.
This guide gets you started building Java app lications for Oracle8i. Working from
simple examp les, you quickly learn h ow to load, pu blish, and call Java stored
procedures.
Major Topics
s Who Shou ld Read This Guide?
s How This Guide Is Organized
s Notational Conventions
s Sample Database Tables
s Related Publications
s Suggested Read ing
8/8/2019 Java Stored
10/118
viii
Who Should Read This Guide?Anyon e developing Java ap plications for Oracle8i will benefit from read ing this
guid e. Written especially for p rogrammers, it w ill also be of value to architects,
systems analysts, project managers, and oth ers interested in netw ork-centric
da tabase applications. To use this guid e effectively, you m ust h ave a w orking
know ledge of Java, SQL, PL/ SQL, and Oracle8i.
How This Guide Is OrganizedThis guide is divided into the following five chap ters:
Chapter 1, "Introduction" After discussing Javas synergy with the Oracle RDBMS,
this chap ter surveys the main features of stored procedu res and points out theadvantages they offer. Then, you learn h ow the Au rora JVM and its ma in
comp onents work w ith Oracle8i. The chapters ends w ith an overv iew of the Java
stored procedures development process.
Chapter 2, "Loading Stored Procedures" This chapter shows you how to load
Java source, class, and resource files into the RDBMS. You learn how to manage Java
schema objects using the loadjava an d dropjava utilities. Also, you learn abou t
name resolution and invoker versus d efiner rights.
Chapter 3, "Publishing Stored Procedures" This chapter shows you how to
pu blish Java classes to SQL. Among other things, you learn how to write call
specifications, map datatypes, and set parameter modes.
Chapter 4, "Calling Stored Procedures" This chap ter show s you h ow to call Java
stored p rocedu res in various contexts. For examp le, you learn how to call Java from
SQL DML statements, database triggers, and PL/ SQL blocks.
Chapter 5, "Developing an Application" This chapter ties together w hat you have
learned. Step by step, it walks you th rough the d evelopmen t of a Java stored
procedures application.
Note: This guid e presum es you are an experienced Java programm er.
If you are just learn ing Java, see "Suggested Reading" on page xii.
8/8/2019 Java Stored
11/118
ix
Notational ConventionsThis guide follows these conventions:
Java code examp les follow these conventions:
Convention Meaning
Italic Italic font denotes terms being defined for the first time, wordsbeing emphasized, error messages, and book titles.
Courier Courier font d enotes Java, PL/ SQL, and SQL code, schemaobject nam es, program nam es, file names, and p ath n ames.
Convention Meaning
{ } Braces enclose a block of statements.
// A dou ble slash begins a single-line commen t, which extends tothe end of a line.
/* */ A slash-asterisk and an asterisk-slash delimit a mu lti-linecomm ent, which can span mu ltiple lines.
... An ellipsis shows that statements or clauses irrelevant to thediscussion were left out.
lower case Lower case is used for keyword s and for one-word names ofvariables, methods, and packages.
UPPER CASE Upp er case is used for names of constants (static finalvariables) and for names of supplied classes that map tobuilt-in SQL datatyp es.
Mixed Case Mixed case is used for nam es of classes and interfaces and formulti-word names of variables, methods, and packages. Thenames of classes and interfaces begin with an upper-case letter.In all multi-word names, the second and succeeding word sbegin with an up per-case letter.
8/8/2019 Java Stored
12/118
x
PL/ SQL code examp les follow th ese conventions:
Syntax d efinitions use a simp le variant of Backus-Naur Form (BNF) that includes
the following symbols:
Convention Meaning
-- A double hyphen begins a single-line comment, which extendsto the end of a line.
/* */ A slash-asterisk and an asterisk-slash d elimit a m ulti-linecomment, wh ich can span mu ltiple lines.
... An ellipsis shows that statements or clauses irrelevant to the
discussion were left out.
lower case Lower case is used for n ames of constants, variables, cursors,exceptions, subprograms, and packages.
UPPER CASE Upp er case is used for keywords, names of predefinedexceptions, and names of sup plied PL/ SQL packages.
Mixed Case Mixed case is used for names of user-defined datatypes andsubtypes. The nam es of user-defined types begin with an
up per-case letter.
Symbol Meaning
[ ] Brackets enclose optiona l items.
{ } Braces enclose items of which only on e is required .
| A vertical bar separates alternatives w ithin brackets or braces.
... An ellipsis shows that the p receding syntactic element can berepeated.
delimiters Delimiters other than br ackets, braces, vertical bars, and
ellipses must be entered as shown.
8/8/2019 Java Stored
13/118
xi
Sample Database TablesMost programming examples in this guide use tw o samp le database tables named
dept an d emp. Their definitions follow:
CREATE TABLE dept (deptno NUMBER(2) NOT NULL,
dname VARCHAR2(14),
loc VARCHAR2(13));
CREATE TABLE emp (empno NUMBER(4) NOT NULL,
ename VARCHAR2(10),
job VARCHAR2(9),
mgr NUMBER(4),
hiredate DATE,
sal NUMBER(7,2),
comm NUMBER(7,2),
deptno NUMBER(2));
Respectively, the dept an d emp tables contain th e following row s of data:
DEPTNO DNAME LOC
------- ---------- ---------
10 ACCOUNTING NEW YORK
20 RESEARCH DALLAS
30 SALES CHICAGO
40 OPERATIONS BOSTON
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
----- ------- --------- ------ --------- ------ ------ -------7369 SMITH CLERK 7902 17-DEC-80 800 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7566 JONES MANAGER 7839 02-APR-81 2975 20
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7876 ADAMS CLERK 7788 23-MAY-87 1100 20
7900 JAMES CLERK 7698 03-DEC-81 950 30
7902 FORD ANALYST 7566 03-DEC-81 3000 20
7934 MILLER CLERK 7782 23-JAN-82 1300 10
To create and load the tables, run the script demobld.sql, which can be foun d in
the SQL*Plus d emo d irectory.
8/8/2019 Java Stored
14/118
xii
Related PublicationsOccasionally, this guid e refers you to the following Oracle publications for m ore
information:
Oracle8i A pplication Developers Guide - Fundamentals
Oracle8i Java Developers Guide
Oracle8i JDBC Developers Guide and Reference
Oracle8i SQLJ Developers Guide and Reference
Oracle8i SQL Reference
PL/SQL Users Guide and ReferenceSQL*Plus Users Guide and Reference
Suggested ReadingThe Java Programming Language by Arnold & Gosling, Ad dison-Wesley, 1998
Coauth ored by the originator of Java, this definitive book explains the basic
concepts, areas of app licability, and design p hilosophy of the language. Using
nu merou s examp les, it progresses systematically from basic to advanced
programm ing techniques.
Thinking in Java by Bruce Eckel, Prentice Hall, 1998
This book offers a complete introdu ction to Java on a level app ropriate for both
beginners and experts. Using simp le examp les, it presents the fun dam entals and
complexities of Java in a straightforward , good-hum ored w ay.
Core Java by Cornell & Horstmann, Prentice-Hall, 1996
This book is a complete, step-by-step introd uction to Java p rogramming principles
and techniques. Using real-world examples, it highlights alternative app roaches to
program d esign and offers many programm ing tips and tricks.
Java in a Nutshell by Flanagan , OReilly, 1997
This ind ispensable quick reference provides a wealth of information abou t Javas
most comm only used features. It includ es programming tip s and tr aps, excellent
examples of problem solving, and tu torials on imp ortant features.
Java Software Solutions by Lewis & Loftus, Addison-Wesley, 1998
This book provides a clear, thorough introdu ction to Java and object-oriented
programm ing. It contains extensive reference material and excellent p edagogy
includ ing self-assessment questions, program ming projects, and exercises that
encourage experimentation.
8/8/2019 Java Stored
15/118
xiii
Online Sources
There are man y u seful on line sou rces of information abou t Java. For example, youcan view or dow nload gu ides and tutorials from th e Sun Microsystems home p age
on th e Web:
http://www.sun.com
Another popu lar Java Web site is
http://www.gamelan.com
For Java API docum entation, visit
http://www.javasoft.com
Also, the following Internet news grou ps are d edicated to Java:
comp.lang.java.programmer
comp.lang.java.misc
8/8/2019 Java Stored
16/118
xiv
8/8/2019 Java Stored
17/118
Introduction 1-1
1Introduction
Oracle8i has the ap plication d evelopm ent features needed to build a new
generation of soph isticated ap plications at low cost. Chief among th ose features are
stored p rocedures, wh ich op en the Oracle RDBMS to all Java p rogrammers. With
stored p rocedures, you can imp lement bu siness logic at the server level, thereby
improving app lication performance, scalability, and security.
Major Topics
s Java in the RDBMS: A Robust Combinat ion
s Stored Procedu res and Run-Time Contexts
s Advantages of Stored Procedu res
s
The Aurora JVM and Its Comp onentss Developing Stored Procedu res: An O verview
8/8/2019 Java Stored
18/118
Java in the RDBMS: A Robust Combination
1-2 Oracle8i Java Stored Procedures Developers Guide
Java in the RDBMS: A Robust CombinationThe Oracle RDBMS provides Java app lications w ith a dynam ic data-processing
engine, which supports comp lex queries and various views of the same data . All
client requests are assembled as data queries for imm ediate processing, and query
results are generated on the fly.
Several features make Java id eal for server p rogramming. Java lets you assemble
applications using off-the-shelf software components (JavaBeans). Its type safety
and automatic memory management allow for tight integration with the RDBMS. In
addition, Java supports the transparent distribution of application componentsacross a netw ork.
Thus, Java and the RDBMS sup port th e rapid assembly of compon ent-based,
network-centric applications that can evolve gracefully as business needs change. In
addition, you can move app lications and d ata stores off the desktop an d onto
intelligent netw orks and netw ork-centric servers. More impor tant, you can access
those app lications and da ta stores from an y client device.
Figure 11 show s a traditional two-tier, client/ server configu ration in wh ich clientscall Java stored p rocedu res the same way th ey call PL/ SQL stored p rocedures.
(PL/ SQL is an advanced 4GL tightly integrated w ith Oracle8i.) The figu re also
shows how the N et8 Connection Manager can funnel man y netw ork connections
into a single d atabase connection. This enables the RDBMS to sup port a large
number of concurrent users.
Figure 11 Two-Tier Client/Server Configuration
Oracle Database Server
PL/SQL StoredProcedure
RelationalData
Object-Relational Data
Net8Connection
Manager
Net8
Net8 Net8
Net8
ODBC
Client
Pro*
Client
OCI
Client
JDBCDriver
JavaApplet
Oracle Forms / Oracle Reports
Thin Client
Java StoredProcedure
Fat Client
NC
8/8/2019 Java Stored
19/118
Stored Procedures and Run-Time Contexts
Introduction 1-3
Stored Procedures and Run-Time ContextsStored p rocedu res are Java m ethods pu blished to SQL and stored in an Oracle
database for general use. To publish Java m ethods, you w rite call specifications (call
specs for short), wh ich m ap Java m ethod n ames, parameter types, and return types
to their SQL coun terpa rts.
Unlike a wrapp er, which ad ds an other layer of execution, a call spec simply
pu blishes the existence of a Java m ethod . So, when you call the meth od (throu gh its
call spec), the run -time system dispa tches the call with m inimal overhead .
When called by client app lications, a stored p rocedu re can accept argu men ts,
reference Java classes, and return Java result values. Figure 12 shows a procedure
stored in the da tabase and called by various app lications.
Figure 12 Calling a Stored Procedure
Except for graphical-user-interface (GUI) method s, any Java m ethod can ru n in theRDBMS as a stored procedu re. The ru n-time contexts are:
s functions and procedu res
s database triggers
s object-relational methods
The next three sections describe these contexts.
Database Server
hire_emp(...)
Applications
code
hire_emp(...);
Program.
hire_emp(...);
hire_emp(...);
Stored Procedure
8/8/2019 Java Stored
20/118
Stored Procedures and Run-Time Contexts
1-4 Oracle8i Java Stored Procedures Developers Guide
Functions and Procedures
Functions and p rocedu res are nam ed blocks that encapsu late a sequence ofstatements. They are like building blocks that you can use to construct mod ular,
ma intainable applications.
Generally, you use a procedure to perform an action and a function to comp ute a
value. So, for void Java m ethods, you use p rocedure call specs, and for
value-returning methods, you u se fun ction call specs.
Only top-level and packaged (not local) PL/ SQL fun ctions and procedu res can be
used as call specs. When you d efine them using the SQL CREATE FUNCTION,CREATE PROCEDURE, and/ or CREATE PACKAGE statement, they are stored in the
da tabase, where they are available for general use.
Java m ethod s pu blished as functions and p rocedu res must be invoked explicitly.
They can accept argum ents and are callable from:
s SQL CALL statements
s PL/ SQL blocks, subp rograms, and packages
Java m ethod s pu blished as functions are also callable from:
s SQL DML statements (INSERT, UPDATE, DELETE, and SELECT).
Database TriggersA da tabase trigger is a stored procedu re associated w ith a specific table or view.
Oracle invokes (fires) the trigger au tomatically when ever a given DML opera tionmod ifies the table or view.
A trigger has three par ts: a triggering event (DML operation), an optional trigger
constraint, and a trigger action. When the event occurs, the trigger fires and a CALL
statement calls a Java m ethod (through its call spec) to perform th e action.
Database triggers, which you define using the SQL CREATE TRIGGER statement, let
you customize the RDBMS. For example, they can restrict DML operations to
regular business hou rs. Typically, triggers are u sed to en force comp lex businessrules, derive column values au tomatically, prevent invalid tran sactions, log events
transp arently, aud it transactions, or gather statistics.
8/8/2019 Java Stored
21/118
Stored Procedures and Run-Time Contexts
Introduction 1-5
Object-Relational Methods
A SQL object type is a user-defined composite datatype th at encapsu lates a set ofvariables (attributes) with a set of operations (methods), wh ich can be w ritten in Java.
The data structure formed by the set of attributes is pu blic (visible to client
programs). However, well-behaved programs do not manipulate it directly. Instead,
they use the set of methods p rovided .
When you define an object type using the SQL CREATE ... OBJECT statement, you
create an abstract temp late for some real-world object. The temp late specifies only
those attributes and behaviors the object will need in the app lication environment.At run time, when you fill the data structure w ith values, you create an instance of
the object type. You can create as many instances (objects) as you need .
Typically, an object typ e correspond s to som e business entity such as a p urchase
order. To accomm odate a var iable num ber of items, object types can u se
variable-length ar rays (varrays) and nested tables. For example, this feature en ables
a pu rchase order object type to contain a variable num ber of line items.
8/8/2019 Java Stored
22/118
Advantages of Stored Procedures
1-6 Oracle8i Java Stored Procedures Developers Guide
Advantages of Stored ProceduresTo help you build p owerful da tabase app lications, stored p rocedu res provideseveral advantages including better performance, higher prod uctivity, ease of use,
and increased scalability.
PerformanceStored p rocedu res are comp iled once and stored in executable form, so procedu re
calls are qu ick and efficient. Executable code is au tomatically cached and shared
among users. This lowers memory requirements and invocation overhead.
By group ing SQL statements, a stored p rocedu re allows them to be executed with a
single call. This minimizes the u se of slow netw orks, reduces netw ork traffic, and
imp roves round -trip response time. OLTP app lications, in p articular, benefit
because result set processing eliminates network bottlenecks.
Additionally, stored p rocedures enable you to take advantage of the comp uting
resources of the server. For example, you can move comp utation-boun d p rocedures
from client to server, where they will execute faster. Likewise, stored functions
called from SQL statements enh ance performance by executing app lication logic
within the server.
Productivity and Ease of UseBy designing ap plications around a common set of stored p rocedu res, you can
avoid red un dan t coding and increase your p rodu ctivity. Moreover, stored
procedu res let you extend the fun ctionality of the RDBMS. For examp le, stored
functions called from SQL statements enh ance the p ower of SQL.
You can use the Java integra ted developm ent env ironmen t (IDE) of your choice to
create stored procedu res. Then, you can d eploy them on any tier of the netw ork
architecture. Moreover, they can be called by standard Java interfaces such as JDBC,
CORBA, and EJB and by p rogrammat ic interfaces and developm ent tools such as
SQLJ, the OCI, Pro*C/ C++, and JDevelop er.
This broad access to stored procedu res lets you share bu siness logic across
app lications. For example, a stored p rocedu re that imp lements a business rule can
be called from various client-side ap plications, all of wh ich can share tha t bu siness
rule. In ad dition, you can leverage the server s Java facilities w hile continuing to
write app lications for your favorite program matic interface.
8/8/2019 Java Stored
23/118
Advantages of Stored Procedures
Introduction 1-7
Scalability
Stored procedu res increase scalability by isolating ap plication p rocessing on theserver. In ad dition, autom atic dep end ency tracking for stored p rocedu res aids the
developm ent of scalable app lications.
The shared memory facilities of the Multi-Threaded Server (MTS) enable Oracle8i to
sup port more than 10,000 concurrent users on a single nod e. For m ore scalability,
you can u se the Net8 Connection Manager to m ultiplex Net8 connections.
MaintainabilityOnce it is validated , a stored p rocedu re can be used with confid ence in any n um ber
of app lications. If its definition changes, only the p rocedu re is affected, n ot the
app lications tha t call it. This simplifies maintenan ce and en hancement. Also,
mainta ining a procedu re on the server is easier than m aintaining copies on various
client m achines.
InteroperabilityWithin the RDBMS, Java conforms fully to th eJava Language Specification an d
furnishes all the ad vantages of a general-purpose, object-oriented p rogramming
language. Also, like PL/ SQL, Java provid es full access to Oracle data, so any
procedu re written in PL/ SQL can be written in Java.
PL/ SQL stored p rocedu res complemen t Java stored p rocedu res. Typically, SQL
programm ers who wan t procedural extensions favor PL/ SQL, and Java
program mers w ho want easy access to Oracle da ta favor Java.
The RDBMS allows a high degree of interoperability betw een Java an d PL/ SQL.
Java ap plications can call PL/ SQL stored procedu res using an em bedd ed JDBC
dr iver. Conversely, PL/ SQL ap plications can call Java stored procedu res d irectly.
Security
You can restrict access to Oracle data by allowing users to man ipu late the data onlythrough stored procedures that execute with their definers privileges. For example,
you can allow access to a procedu re that up da tes a database table, but d eny access
to the table itself.
Ad t f St d P d
8/8/2019 Java Stored
24/118
Advantages of Stored Procedures
1-8 Oracle8i Java Stored Procedures Developers Guide
Replication
With Oracle Advanced Replication, stored p rocedures can be rep licated (copied)from one O racle8i database to another. This feature m akes them ideal for
imp lementing a central set of business rules. Once wr itten, the stored p rocedures
are replicated an d distributed to work groups and branch offices throughout the
company. In th is way, policies can be revised on a central server rather than on
individual servers.
The Aurora JVM and Its Components
8/8/2019 Java Stored
25/118
The Aurora JVM and Its Components
Introduction 1-9
The Aurora JVM and Its ComponentsOracles Java Virtual Machine (know n as the "Au rora JVM") is a complete, JDK
1.1.6-compliant Java execution environment. The Au rora JVM ru ns in the sam e
process space and address space as the RDBMS kernel, sharing its memory heap s
and directly accessing its relational d ata. This design op timizes mem ory use and
increases throughput.
The Aurora JVM provides a run -time en vironmen t for Java objects. It fully supports
Java d ata structures, method dispa tch, exception han dling, and language-level
thread s. It also sup ports all the core Java class libraries includ ing java.lang,java.io, java.net, java.math, and java.util. Figure 13shows its ma in
components.
Figure 13 Main Components of the Aurora JVM
The Aurora JVM embeds the standard Java n amesp ace in RDBMS schemas. This
featu re lets Java p rograms access Java objects stored in Oracle d atabases and
app lication servers across the enterp rise. In add ition, the JVM is tightly integrated
with the scalable, shared m emory architecture of the RDBMS. Java p rogram s use
call, session, and object lifetimes efficiently without your intervention. So, you can
scale RDBMS and mid dle-tier Java business objects, even w hen they have
session-long state.
SQL Calls
loadjava Utility
CREATE JAVA Statement
IIOP Calls
Aurora JVM
Garbage Collector
Compiled Code
Class Loader
Interpreter &Run-time System
Library Manager Memory Manager
Memory
The Aurora JVM and Its Components
8/8/2019 Java Stored
26/118
The Aurora JVM and Its Components
1-10 Oracle8i Java Stored Procedures Developers Guide
The Aurora JVM versus Client JVMs
This section d iscusses some important d ifferences between th e Aurora JVM andtyp ical client JVMs.
Method main()
Client-based Java app lications d eclare a single, top-level method (main()) that
defines the profile of an application. Like applets, server-based applications have no
such "inner loop." Instead, they are dr iven by logically indep endent clients.
Each client begins a session, calls its server-side logic mod ules via top-levelentryp oints, and eventually end s the session. The server environm ent hides the
managing of sessions, netw orks, and other shared resources from hosted Java
programs.
The GUI
A server cannot p rovide GUIs, but it can p rovide the logic that d rives them. For
example, the Aurora JVM does not supp ly the basic GUI compon ents foun d in theJDKs Abstract Wind ow ing Toolkit (AWT). However, all AWT Java classes are
available within the server environm ent. So, your programs can use AWT
functionality, as long as they do not attem pt to materialize a GUI on the server.
The IDE
The Aurora JVM is oriented to Java ap plication d eploymen t, not d evelopmen t. You
can wr ite and u nit-test app lications in your favorite IDE, then dep loy them for
execution within the RDBMS. A future release will integrate the Aurora JVM with a
variety of client-side IDEs to enable remote d ebugging, p rofiling, test coverage
analysis, and so on.
Javas binary comp atibility allows you to w ork in an y IDE, then up load Java class
files to the server. You n eed n ot move you r Java sou rce files to the RDBMS. Instead ,
you can use p owerful client-side IDEs to maintain Java app lications tha t are
dep loyed on the server.
Multi-threading
Multi-threaded Java p rograms execute on the Oracle8i database server w ithout
mod ification. How ever, in a server environm ent, Java th reads d o notincrease
concurrency (and therefore throughput). Throughput is affected only by MTS mode,
the nu mber of OS processes used by the RDBMS, and va rious tun ing meth ods.
The Aurora JVM and Its Components
8/8/2019 Java Stored
27/118
The Aurora JVM and Its Components
Introduction 1-11
Before porting a multi-threaded app lication to the server, make sure you
un derstan d how thread s work w ith the Aurora JVM. The imp ortant d ifferences are
that on th e server:
s Threads run sequentially, not concur rently.
s Threads within a call die when th e call end s.
s Threads are cooperative, not preemptive, so if one thread enters an infinite loop,
no other threads can run .
Oracle8i mu lti-thread ing refers to concurrent user sessions, notJavamulti-threading. On the server, throughput is increased by supporting many
concurrent user sessions. The scheduling of Java execution (of each call within a
session for example) to maximize through pu t is don e by the RDBMS, not by Java.
Main Components of the Aurora JVMThis section briefly d escribes the main compon ents of the Aurora JVM and some of
the facilities they provid e.
Library Manager
To store Java classes in an Oracle database, you u se the comman d-line utility
loadjava, wh ich em ploys SQL CREATE JAVA statements to do its work. When
invoked by the CREATE JAVA {SOURCE | CLASS | RESOURCE} statement, the
library m anager loads Java source, class, or resource files into the RDBMS. You
never access these Java schema objects directly; only the Aurora JVM uses them.
Memory Manager
Autom ated storage managem ent is one of Javas key features. In p articular, the Java
run-time system requires automatic garbage collection (deallocation of mem ory held
by unused objects). The memory manager uses memory allocation techniques tuned
to object lifetimes. Objects that surv ive beyond call boun dar ies are migrated to
app ropriate memory areas. Also, the m emory m anager m inimizes the footprint p er
session by sharing imm utable object state such as class definitions and final staticvariables.
The Aurora JVM and Its Components
8/8/2019 Java Stored
28/118
p
1-12 Oracle8i Java Stored Procedures Developers Guide
Compiler
The Aurora JVM includ es a stand ard JDK 1.1.6-comp atible Java com piler. Wheninvoked by th e CREATE JAVA SOURCE statement, it tr anslates Java sou rce files into
architecture-neutr al instructions called bytecodes. Each bytecode consists of an
opcode followed by its operand s. The resu lting Java class files, wh ich conform fully
to the Java stand ard, are submitted to the interpreter at run time.
Interpreter
To execute Java programs, the Aurora JVM includes a standard JDK1.1.6-compatible
bytecode interpreter. The interpreter and associated Java ru n-time system execute
stand ard Java class files. For high throu ghp ut, the interpreter ru ns on the
Multi-Thread ed Server, which m anages sessions and sched ules the execution of
Java program s. The run-time system sup ports native method s and call-in/ call-out
from the host environment.
Class Loader
In response to requ ests from the ru n-time system, the Java class loader locates,
loads, and in itializes Java classes stored in the RDBMS. The class loader read s the
class, then genera tes the data structures needed to execute it. Immutable data and
metad ata are loaded into initialize-once shared m emory. As a result, less memory isrequired per session. The class loader attemp ts to resolve external references wh en
necessary. Also, it invokes the Java compiler automatically when Java class files
mu st be recomp iled (and th e source files are available).
Verifier
Java class files are fully portable and conform to a w ell-defined format. The verifier
preven ts the inad vertent u se of "spoofed" Java class files, which might alterprogram flow or violate access restrictions. Oracle security and Java security w ork
with th e verifier to protect your app lications and d ata.
Note: Although your ow n code is interp reted, the Aurora JVM uses
natively compiled versions of the core Java class libraries, object requestbroker (ORB), and JDBC drivers. See "JServer Accelerator" on page 1-13.
The Aurora JVM and Its Components
8/8/2019 Java Stored
29/118
Introduction 1-13
Server-Side JDBC Driver
JDBC is a stand ard set of Java classes providing ven dor-indep end ent access torelational d ata. Specified by Sun Microsystems and mod eled after ODBC (Open
Database Connectivity) and the X/ Op en SQL CLI (Call Level Interface), the JDBC
classes sup ply stand ard features such as simu ltaneous connections to several
databases, transaction man agemen t, simp le queries, calls to stored procedu res, and
streaming access to LONG column d ata.
Using low-level entry points, a specially tuned JDBC d river runs d irectly inside the
RDBMS, thereby provid ing the fastest access to Oracle da ta from Java stored
procedu res. The server-side JDBC dr iver comp lies fully w ith the Sun JDBC
specification. Tightly integrated with the RDBMS, it supports Oracle-specific
datatypes, NLS character sets, and stored p rocedu res. Also, the client-side and
server-side JDBC APIs are the same, w hich makes it easy to par tition app lications.
Server-Side SQLJ Translator
SQLJ enables you to embed SQL statements in Java programs. It is more concise
than JDBC and more am enable to static analysis and type checking. The SQLJpreprocessor, itself a Java program, takes as input a Java source file in which SQLJ
clauses are embedded. Then, it translates the SQLJ clauses into Java class definitions
that imp lement the sp ecified SQL statements. The Java typ e system ensures that
objects of those classes are called with the correct arguments.
A highly optimized SQLJ Translator runs directly inside the RDBMS, where it
provides run-time access to Oracle data via the server-side JDBC driver. SQLJ forms
can include queries, DML, DDL, transaction control statements, and calls to storedprocedu res. The client-side and server-side SQLJ APIs are the sam e, wh ich m akes it
easy to partition applications.
JServer Accelerator
The JServer Accelerator is a n ative-code compiler that speed s up the execution of
Java p rograms by eliminating interp reter overhead . (See Figure 14 on page 1-14.) It
translates stand ard Java class files into specialized C source files that are p rocessed
by a platform-dep end ent C compiler into native libraries, which the Aurora JVM
can load dyn amically.
Unlike just-in-time (JIT) compilers, the JServer Accelerator is portable to all OS and
hard ware platforms. To speed u p you r applications, the Aurora JVM is sup plied
with natively compiled versions of the core Java class libraries, embedded ORB, and
JDBC d rivers.
The Aurora JVM and Its Components
8/8/2019 Java Stored
30/118
1-14 Oracle8i Java Stored Procedures Developers Guide
Figure 14 Interpreter versus JServer Accelerator
Java Source Code
Java Bytecode
C Source Code
Native Code
Java Compiler
Java Interpreter JServer Accelerator
Platform C Compiler
Execution Speed = X
Execution Speed = 10X
Developing Stored Procedures: An Overview
8/8/2019 Java Stored
31/118
Introduction 1-15
Developing Stored Procedures: An OverviewTo d evelop Java stored procedu res, take the four steps listed below. For a detailedexample showing the design and im plemen tation of a Java stored procedu res
app lication, see Chapter 5.
Write or Reuse the ProceduresUse your favorite Java IDE to write the p rocedu res, or simp ly reuse existing
procedu res that meet your needs. Oracles Java facilities supp ort a variety of Java
developm ent tools and client-side p rogrammat ic interfaces. For examp le, the
Aurora JVM accepts p rograms developed in pop ular Java IDEs such as Symantecs
Visual Caf, Oracles JDeveloper, and Borlands JBuilder.
Load the Procedures into the RDBMSLoad th e Java sou rce, class, and resou rce files into th e Oracle RDBMS using the
loadjava command -line u tility, wh ich allows you to specify several op tions. For
more information, see Chapter 2.
Publish the Procedures in the Oracle Data DictionaryFor each Java method that is callable from SQL, write call a spec, which exposes the
methods top-level entry p oint to Oracle. For m ore information, see Chapter 3.
Call the Procedures from SQL and PL/SQLCall your Java stored procedu res directly from SQL DML statemen ts and from
PL/ SQL blocks and subp rogram s. Also, using the SQL CALL statement, call the
stored p rocedures from th e top level (in SQL*Plus for example) and from d atabase
triggers. For m ore information, see Chapter 4.
Developing Stored Procedures: An Overview
8/8/2019 Java Stored
32/118
1-16 Oracle8i Java Stored Procedures Developers Guide
8/8/2019 Java Stored
33/118
Loading Stored Procedures 2-1
2Loading Stored Procedures
Before you can call Java stored procedu res, you m ust load them into the Oracle
RDBMSand publish them to SQL. Loading and publishing are separate tasks. Many
Java classes, referenced only by other Java classes, are never published to SQL.
To load Java stored procedu res autom atically, you u se the comm and -line u tility
loadjava. It up loads Java source, class, and resource files into a system-generateddatabase table, then u ses the SQL CREATE JAVA {SOURCE | CLASS | RESOURCE}
statem ent to load the Java files into the RDBMS. You can up load Java files from OS
file systems, popu lar Java IDEs, intran ets, or the Internet.
Note: To load Java stored procedu res man ually, you u se CREATE JAVA statements.For examp le, in SQL*Plus, you can use the CREATE JAVA CLASS statement to load
Java class files from local BFILEs and LOB columns into the RDBMS. For more
information, see the Oracle8i SQL Reference.
Major Topics
s Java in th e Database
s Managing Java Schema Objects
s Using loadjava
s Using drop java
s Invoker Rights versus Definer Rights
Java in the Database
8/8/2019 Java Stored
34/118
2-2 Oracle8i Java Stored Procedures Developers Guide
Java in the Database
To make Java files available to the Au rora JVM, you m ust load them into theRDBMS as schema objects. As Figure 21 shows, loadjava can invoke the JVMs
Java compiler, wh ich compiles source files into stand ard class files.
The figure also shows that loadjava can set the values of options stored in a
system d atabase table. Among oth er things, these options affect the processing of
Java sou rce files. For examp le, the op tion -encoding localizes Java source files by
specifying their character-encoding scheme. (For m ore information abou t the
options table, see "Passing Options to the Comp iler" on page 2-8.)
Figure 21 Loading Java into the RDBMS
.class file .jar file.java file
loadjava
ResourceSource ClassClass
RDBMS
Options
TableJava
Compiler
Java Java Java Java
Schema
8/8/2019 Java Stored
35/118
Managing Java Schema Objects
8/8/2019 Java Stored
36/118
2-4 Oracle8i Java Stored Procedures Developers Guide
Managing Java Schema Objects
To m anage Java schem a objects, you u se the comm and -line u tilities loadjava an ddropjava. You can w rite, compile, and p artially test and debu g Java stored
procedu res on the client side in p opu lar Java IDEs. Then, you can use loadjava to
upload the resulting Java source, class, and resource files into the RDBMS as schema
objects. In ad dition, you can use dropjava to d rop given Java source, class, and
resource schema objects from your schem a.
What to Load If you create Java class files on the client side, you can use loadjava to uploadthem into the RDBMS. Alternatively, you can up load Java source files and let the
Aurora JVM comp ile them . In m ost cases, it is best to comp ile and debu g programs
on th e client side, then u pload the class files for final testing within the RDBMS.
Loading Java archives (JARs) or ZIP archives is the simp lest way to use loadjava.
Archives cannot be schema objects. Therefore, when passed a JAR or ZIP archive,
loadjava loads the archived files individually. For efficiency, files not modified
since the last time they were loaded are not reloaded.
Two objects in th e same schema cannot d efine the sam e class. For examp le, sup pose
you d efine class X in the file A.java, load the file, then m ove the definition ofX tothe file B.java. An attemp t to load B.java will fail. Instead, either drop A.java
or load a new version of it (wh ich no longer d efines X), then load B.java.
How External References Are ResolvedAll the classes in a Java p rogram mu st be loaded before its external references can
be resolved. One reason for this requirement is that Java program s have multiple
source files because th e JDK and other client-side tools require a separate source filefor each pu blic class. Another reason is that classes often refer to each oth er, so
nam e resolution is not possible until all the files have been loaded .
You can u se loadjava to force early resolution. When you specify the option
-resolve, loadjava uses the SQL ALTER JAVA CLASS ... RESOLVE statement to
resolve external references in uploaded Java classes. All references must be resolved
before you can use those classes. If you do not sp ecify the op tion, Oracle executes
the SQL ALTER JAVA statement implicitly at run time.
Note: loadjava requires uncompressedJARs and ZIP archives that are
not nestedinside another JAR or ZIP archive.
Managing Java Schema Objects
8/8/2019 Java Stored
37/118
Loading Stored Procedures 2-5
If all its references to other classes cann ot be resolved , a class is marked invalid. At
run time, attempts to load an invalid class throw a ClassNotFound exception, as
required by theJava Language Specification.
CLASSPATH versus Resolver Spec
Java classes are loaded dyn amically at ru n time. In Sun 's JDK, the class loader
locates a class by searching sequen tially th rough the list of directories specified by
the environment variable CLASSPATH.
The Aurora JVM uses a similar list called a resolver spec, but instead of directories, it
specifies SQL schemas. When th e JVM searches for a class corresponding to a Java
nam e, it searches the list of schemas sequ entially until a Java schem a object
matching th at nam e is foun d. If the object is not found , an error is generated .
Each class has its ow n resolver sp ec. For examp le, class As resolver sp ec lists the
schemas to be searched for the classes referenced by A. Reference lists are
mainta ined by a facility called the resolver.
Resolution Modes
You can have loadjava resolve classes or d efer resolution u ntil run time. (The
resolver ru ns au tomatically when the JVM tries to load a class that is marked
invalid.) However, it is best to resolve classes before run time to learn of missing
classes early.
You can ru n loadjava in the following th ree resolution modes:
s Load, then resolve: If you specify the op tion -resolve, loadjava up loads allclasses listed on the comm and line, marks them invalid, and then resolves
them . Use this mod e wh en loading classes that refer to each other, or when
reloading isolated classes. Any class that d epend s on classes not yet loadedremains marked invalid.
s Load and resolve: If you specify the op tion -andresolve, loadjava resolveseach class as it is loaded . In genera l, this mod e is not recomm ended because it
can leave classes that h ave unresolved references marked valid, causing an
error at run time.
Note: loadjava resolves references to classes but not to resou rces. So,
make sure th e resource files that your classes need a re loaded correctly.
Managing Java Schema Objects
8/8/2019 Java Stored
38/118
2-6 Oracle8i Java Stored Procedures Developers Guide
s Defer resolution: If you specify neither -resolve nor -andresolve, loadjavaloads files but d oes not comp ile or resolve them . Instead , files are compiled (if
necessary), and resolved a t run time or w hen th e JVM needs their defin itions toresolve other classes. If you defer resolution until all classes for an application
are loaded , the resolver never h as to mark a class invalid because it refers to
classes not yet loaded . For that reason, this is the p referred m ode.
Kinds of Resolver Specs
The option -resolver binds a resolver spec to th e class schema objects that
loadjava creates or replaces. Alternatively, a p redefined resolver spec can beboun d to class schema objects by the option -oracleresolver (the default). In
most cases, the pred efined resolver spec will meet your needs.
A resolver spec lists one or more items, each consisting of a nam e spec and schem a
spec in the following form:
"((name_spec schema_spec) [(name_spec schema_spec)] ...)"
A name spec is similar to a name in a Java impor t statement. It can be a Java class fu llname, a p ackage name wh ose final element is the w ildcard "*", or just tha t
wildcard. However, the elemen ts of a nam e spec must be separated by slashes, not
periods. For example, the name spec a/b/* matches all class names that begin with
a.b. The special name spec, "*", matches all class names.
A schema spec can be a schema n ame or the w ildcard "-". The w ildcard does not
identify a schema; it tells the resolver not to mark a class invalid even if a reference
cannot be resolved. (Withou t the w ildcard "-" in a resolver spec, an u nresolved
reference invalida tes the class and generates an error.) Use wildcard "-" when you
want unresolved references to be detected at run time rather than load time.
Managing Java Schema Objects
8/8/2019 Java Stored
39/118
Loading Stored Procedures 2-7
When searching for a schem a object whose nam e matches the name spec, the
resolver looks in the schema d esignated by the schema sp ec. The resolver searches
schemas in the ord er they are listed in the resolver spec. For examp le,
-resolver "((* SCOTT) (* PUBLIC))"
means "Search for a reference in schema SCOTT, then in schema PUBLIC. If a
reference is not resolved, mark the referring class invalidand display an error
message. In other words, call attention to missing classes". For user SCOTT, this
resolver spec is equivalent to the -oracleresolver spec.
For another example,
-resolver "((* SCOTT) (* PUBLIC) (* -))"
means "Search for a reference in schema SCOTT, then in schema PUBLIC. If the
reference is not resolved, mark the referring class validand do not d isplay an error
message. In other words, ignore m issing classes".
What the Digest Table Doesloadjava uses the hash table JAVA$CLASS$MD5$TABLE (called "digest table"
from here on) to tr ack the load ing of Java schema objects into a given schema. (MD5
refers to RSA Data Securitys MD5 Message-Digest Algorithm, which does the
hashing.) If you u se loadjava to load a Java schema object, you m ust u se
dropjava to d rop th e object. Otherw ise, the digest table is not up da ted p roperly. If
that happ ens, specify the option -force to bypass the digest table lookup .
The digest table enables loadjava to skip files that have not changed since theywere last loaded . This improves the p erformance of makefiles and scripts tha t
invoke loadjava for a w hole list of files.
loadjava detects unchanged files by maintaining a d igest table in every schema.
The digest table relates a filename to a digest, which is a hash of the files content.
Comp aring d igests compu ted for the same file at different times is a fast way to
detect a change in the files content.
For each file it processes, loadjava compu tes a d igest of the files content, then
looks up the filename in the d igest table. If there is a matching entry, loadjava
does not load the file (because a corresponding schema object exists and is up to
date). If you specify the op tion -verbose, loadjava shows you the results of its
digest table lookup s.
Managing Java Schema Objects
8/8/2019 Java Stored
40/118
2-8 Oracle8i Java Stored Procedures Developers Guide
How Compilation Is Done
Loading a sou rce file creates or upd ates a Java sou rce schema object and invalidatesthe class schema objects derived previously from that source file (because they were
not comp iled from the n ewly load ed sou rce file). If the class schema objects do not
exist, they are created.
To force compilation w hen you up load a source file, specify the loadjava option
-resolve. loadjava displays messages inserted by the compiler into the system
database table USER_ERRORS. For a d escription of th is table, see the Oracle8i
Reference.
Passing Options to the Compiler
There are two w ays to pass options to the comp iler. If you specify the op tion
-resolve (which might trigger compilation), then you can specify compiler
options on the loadjava command line. You can also set compiler option values in
the da tabase table JAVA$OPTIONS (called "opt ions tab le" from here on). Then, you
can selectively override th ose settings using loadjava command-line options.
A row in the op tions table contains the n ames of source schema objects to which an
option setting app lies. You can use m ultiple row s to set the op tions differently for
d ifferent source schem a objects.
The comp iler looks up op tions in the options table unless they are specified on the
loadjava command line. If there is no options-table entry or comm and -line value
for an op tion, the compiler uses the following default va lue (for the n on-default
values, see the Oracle8i SQLJ Developers Guide and Reference):
encoding = latin1
online = true // applies only to SQLJ source files
You can get and set options-table entries using the following functions and
procedu res, which are defined in the sup plied package DBMS_JAVA:
PROCEDURE set_compiler_option(
name VARCHAR2, option VARCHAR2, value VARCHAR2);
FUNCTION get_compiler_option(
name VARCHAR2, option VARCHAR2) RETURNS VARCHAR2;
PROCEDURE reset_compiler_option(
name VARCHAR2, option VARCHAR2);
Managing Java Schema Objects
8/8/2019 Java Stored
41/118
Loading Stored Procedures 2-9
The parameter name is the nam e of a Java p ackage, the full name of a class, or the
emp ty string. After searching th e options table, the comp iler selects the row in
which name most closely matches the full name of the schema object. Ifname is the
emp ty string, it ma tches the name of any schema object.
Initially, a schema d oes not have an options table. To create one, use the p rocedu re
dbms_java.set_compiler_option to set a value. The procedure creates the
table if it does not exist. Enclose param eters in single quotes, as shown in the
following example:
SQL> dbms_java.set_compiler_option('X.sqlj', 'online', 'false');
Using loadjava
8/8/2019 Java Stored
42/118
2-10 Oracle8i Java Stored Procedures Developers Guide
Using loadjava
Using a built-in package named LOADLOBS, the loadjava utility uploads Java filesinto a BLOB colum n in the database table CREATE$JAVA$LOB$TABLE, which the
utility creates in the logon schema. Then, it uses the SQL CREATE JAVA statement to
load the Java files into th e RDBMS as schem a objects.
On the comm and line, you can en ter the names of Java sou rce, class, and resource
files, SQLJ input files (.sqlj files), and un compressed JARs and ZIP archives in
any ord er. Here is the syntax:
loadjava {-user | -u} username/password[@database][-option_name -option_name ...] filename filename ...
where option_name stand s for the following syntax:
{ {andresolve | a}
| debug
| {definer | d}
| {encoding | e} encoding_scheme_name
| {force | f}| {grant | g} {username | role_name}[,{username | role_name}]...
| {oci8 | o}
| oracleresolver
| {resolve | r}
| {resolver | R} "resolver_spec"
| {schema | S} schema_name
| {synonym | s}
| {thin | t}
| {verbose | v} }
To d isplay a h elp screen, use this syntax:
loadjava {-help | -h}
In a list of options or files, names must be separated only by spaces:
-force, -resolve, -thin // No
-force -resolve -thin // Yes
How ever, in a list of users and/ or roles, names m ust be separated only by comm as:
SCOTT, PAYROLL, BLAKE // No
SCOTT,PAYROLL,BLAKE // Yes
Using loadjava
8/8/2019 Java Stored
43/118
Loading Stored Procedures 2-11
Table 21 describes the loadjava command-line options.
Table 21 loadjava Options
Option Description
andresolve Comp iles source files and resolves each class file as it is loaded . Thisoption and -resolve are mu tua lly exclusive. If neither is specified,files are loaded bu t not comp iled or resolved.
In general, this mod e is not recommend ed because it can leave classesthat have unresolved references marked valid, causing an error at runtime. See "Resolution Mod es" on page 2-5.
debug Generates debug information. This option is equivalent to javac -g.
definer Specifies that the methods of up loaded classes will execute w ith thepr ivileges of their definer, not their invoker. By default, method sexecute w ith the p rivileges of their invoker.
Different definers can have different privileges, and an application canhave m any classes, so make su re the meth ods of a given class executeonly with the privileges they need. For more information, see "InvokerRights versu s Definer Rights" on page 2-21.
encoding Sets (or resets) the op tion -encoding in the database tableJAVA$OPTIONS to the specified value, which mu st be the name of astand ard JDK encoding-scheme (the default is latin1). The compileruses this value, so the encoding of uploaded source files must matchthe specified encoding.
force Forces the loading of Java class files wh ether or not th ey have beenloaded before. By d efault, previously loaded class files are rejected.You cannot force the loading of a class file if you previously loaded the
source file. You m ust d rop the source schem a object first.
grant Grants the EXECUTE pr ivilege on up loaded classes to the listed usersand / or roles. (To call the method s of a class directly, users mu st havethe EXECUTE privilege.)
This option is cumulative. Users and roles are added to the lis t of thosehaving the EXECUTE privilege.
To revoke the p rivilege, either d rop an d reload the schema objectwithout specifying -grant, or use the SQL REVOKE statement. Togrant the privilege on an object in another users schema, you musthave the CREATE PROCEDURE WITH GRANT privilege.
oci8 Directs loadjava to comm unicate with the database using the OCIJDBC d river. This op tion (the defau lt) and -thin are mutu allyexclusive.
Using loadjava
8/8/2019 Java Stored
44/118
2-12 Oracle8i Java Stored Procedures Developers Guide
oracleresolver Binds n ewly created class schema objects to the following p redefinedresolver spec:
"((* definer's_schema) (* public))"
This option (the defau lt) detects missing classes imm ediately. It and-resolver are mu tually exclusive.
resolve After all class files on the comm and line are loaded and compiled (ifnecessary), resolves all external references in those classes. If this
option is not specified, files are loaded bu t not compiled or resolveduntil run time.
Specify this option to comp ile (if necessary) and resolve a class thatwas load ed p reviously. You n eed not specify the op tion -forcebecause resolution is don e indep endently, after loading.
resolver Binds n ewly created class schema objects to a u ser-defined resolverspec. Because it contains spaces, the resolver spec m ust be enclosed bydou ble quotes. This option and -oracleresolver (the default) are
mutually exclusive.
schema Assigns new ly created Java schema objects to th e specified schema. Ifthis option is not specified, then the logon schema is used.
You m ust hav e the CREATE ANY PROCEDURE pr ivilege to load intoanother u sers schema.
synonym Creates a public synonym for uploaded classes, making themaccessible out side the schema into wh ich th ey are loaded. To specifythis option, you mu st have the CREATE PUBLIC SYNONYM privilege.
If you specify this op tion for sou rce files, it also app lies to classescompiled from those source files.
thin Directs loadjava to commun icate with the d atabase using the th inJDBC driver. This option and -oci8 (the default) are mutuallyexclusive.
verbose Enables verbose mode, in which progress messages are displayed.
Table 21 (Cont.) loadjava Options
Option Description
Using loadjava
8/8/2019 Java Stored
45/118
Loading Stored Procedures 2-13
Specifying the User
The argum ent -user specifies a username, passw ord, and d atabase connect stringin the following format:
username/password[@database]
Files are loaded into the d esignated d atabase instance. With option -oci8 (the
default), the connect string database is optional. Ifdatabase is specified, it can
be a TNS name or a N et8 name-value list. If it is not specified, then the users
default database is used.
With option -thin, the connect string database mu st be specified in this format:
@host:lport:SID
where host names the h ost compu ter, lport is the port configu red to listen for
Net8 connections (the default is 5521), and SID is the database system identifier
(the default is ORCL).
Specifying FilenamesOn th e comm and line, you can enter a s many nam es of Java source, class, and
resource files, SQLJ inpu t files, and un compressed JARs and ZIP archives as you
like, in any order. Archives cannot be schema objects. Therefore, when passed a JAR
or ZIP archive, loadjava loads the archived files individually.
The best way to upload files is to store them in a JAR or ZIP archive. By loading
archives, you avoid schema object naming complications (discussed below). If youhave a JAR or ZIP archive that works with the JDK, you can be sure tha t it will also
work with loadjava.
The nam es of schem a objects d iffer slightly from filenames, and different schema
objects have different naming conventions. Class files are self-identifying, so
loadjava can map their filenames to the nam es of schema objects autom atically.
loadjava can also map source filenames au tomatically. It simp ly gives the schema
object the fu ll name of the first class defined in the file. Likewise, JARs and ZIP
archives include th e nam es of the files they contain.
How ever, resource files are not self identifying; loadjava derives the names of
Java resource schema objects from th e literal nam es you enter on the command -line
(or the literal names in a JAR or ZIP archive). Resource schema objects are used by
run ning p rograms, so make su re you enter resource filenames correctly.
Using loadjava
8/8/2019 Java Stored
46/118
2-14 Oracle8i Java Stored Procedures Developers Guide
The best way to load ind ividua l resource files is to run loadjava from the top of
the package tree, specifying resource filenames relative to that directory. If you
decide not to follow that rule, the d etails of resource file nam ing follow.
When you load a resource file,loadjava derives the name of the resource schema
object from the filename that you enter on the comm and line. Sup pose you typ e the
following relative and absolute pathnames on the command line:
alpha/beta/x.props
/home/scott/javastuff/alpha/beta/x.props
Although you specified th e same file, load java creates two schema objects:
alpha/beta/x.props
ROOT/home/scott/javastuff/alpha/beta/x.props
loadjava prefixes ROOT to the second n ame because th e nam es of schema objects
cannot begin with a slash (/).
Classes can refer to resource files relatively (for example, b.props) or absolutely
(for example, /a/b.props). To ensure that loadjava and the class loader use thesame n ame for a resource schema object, enter the nam e that th e class passes to
method getResource() or getResourceAsString().
To make sure the correct names are used, before uploading resource files, store them
in a JAR, as shown in the following examp le:
> cd /home/scott/javastuff
> jar -cf alphaResources.jar alpha/*.props
> loadjava ... alphaResources.jar
Even better, store both the class and resource files in a JAR. That w ay, the follow ing
invocations are equivalent because you can use any p athname to load th e contents
of a JAR:
> loadjava ... alpha.jar
> loadjava ... /home/scott/javastuff/alpha.jar
Using loadjava
8/8/2019 Java Stored
47/118
Loading Stored Procedures 2-15
Examples
In the following example, loadjava connects to the default da tabase using thedefault OCI JDBC driver, load s files from a JAR into schem a BLAKE, then resolves
them:
> loadjava -user scott/tiger -resolve -schema BLAKE serverObjs.jar
In the next example, loadjava connects u sing the thin JDBC dr iver, loads a class
and a resource file, then resolves them:
> loadjava -u scott/tiger@dbhost:5521:orcl -t -r Agent.class \
images.dat
In the final example, loadjava adds NILES an d FORD to the list of users w ho can
execute Manager.class:
> loadjava -thin -user scott/tiger@localhost:5521:orcl \
-grant NILES,FORD Manager.class
Reloading FilesIf you u pload the same file mu ltiple times bu t specify d ifferent opt ions, the op tions
specified for the last u pload prevail. The tw o exceptions are:
s Ifloadjava does not load a file because it matches a d igest table entry, then
most options have no effect on the schema object . However, the options -grant
an d -resolve are always obeyed. To have loadjava skip the d igest table
lookup, specify the op tion -force.
s The option -grant is cum ulative. All the u sers and roles specified in every
up load of a given class in a given schema are gran ted the EXECUTE privilege.
Also, if you use the SQL DROP JAVA statement to d rop a Java class, and then u se
loadjava to reload the same class, you mu st specify the option -force.
Otherw ise, the upload fails.
Using loadjava
8/8/2019 Java Stored
48/118
2-16 Oracle8i Java Stored Procedures Developers Guide
Checking Upload ResultsTo check up load results, you can query th e database view USER_OBJECTS, which
contains information about schema objects own ed by th e user (SCOTT in th is case).
For example, the following SQL*Plus script formats and displays useful information
about Java source, class, and resource schema objects:
SET SERVEROUTPUT ON
SET VERIFY OFF
PROMPT A)ll or J)ava only?
ACCEPT x CHAR PROMPT 'Choice: '
DECLARE
choice CHAR(1) := UPPER('&x');
printable BOOLEAN;
bad_choice EXCEPTION;
BEGIN
IF choice NOT IN ('A', 'J') THEN RAISE bad_choice; END IF;
DBMS_OUTPUT.PUT_LINE(CHR(0));
DBMS_OUTPUT.PUT_LINE('Object Name ' ||
'Object Type Status Timestamp');DBMS_OUTPUT.PUT_LINE('------------------------------ ' ||
'------------- ------- ----------------');
FOR i IN (SELECT object_name, object_type, status, timestamp
FROM user_objects ORDER BY object_type, object_name)
LOOP
/* Exclude objects generated for loadjava and dropjava. */
printable := i.object_name NOT LIKE 'SYS_%'
AND i.object_name NOT LIKE 'CREATE$%'
AND i.object_name NOT LIKE 'JAVA$%'
AND i.object_name NOT LIKE 'LOADLOB%';
IF choice = 'J' THEN
printable := i.object_type LIKE 'JAVA %';
END IF;
IF printable THEN
DBMS_OUTPUT.PUT_LINE(RPAD(i.object_name,31) ||
RPAD(i.object_type,14) ||
RPAD(i.status,8) || SUBSTR(i.timestamp,1,16));END IF;
END LOOP;
EXCEPTION
WHEN bad_choice THEN
DBMS_OUTPUT.PUT_LINE('Bad choice');
END;
/
Using loadjava
8/8/2019 Java Stored
49/118
Loading Stored Procedures 2-17
You can choose to d isplay all you r schema objects or only the Java objects:
SQL> @usr_obj
A)ll or J)ava only?
Choice: a
Object Name Object Type Status Timestamp
----------------------------- ------------- ------- ----------------
Alerter JAVA CLASS VALID 1998-10-08:13:42
POManager JAVA CLASS VALID 1998-10-08:17:14
Alerter JAVA SOURCE VALID 1998-10-08:13:42POManager JAVA SOURCE VALID 1998-10-08:17:11
BONUS TABLE VALID 1998-10-08:14:02
DEPT TABLE VALID 1998-10-08:14:02
EMP TABLE VALID 1998-10-08:14:02
SALGRADE TABLE VALID 1998-10-08:14:02
SQL> @usr_obj
A)ll or J)ava only?
Choice: j
Object Name Object Type Status Timestamp
----------------------------- ------------- ------- ----------------
Alerter JAVA CLASS VALID 1998-10-08:13:42
POManager JAVA CLASS VALID 1998-10-08:17:14
Alerter JAVA SOURCE VALID 1998-10-08:13:42
POManager JAVA SOURCE VALID 1998-10-08:17:11
The column object_name stores the full names of Java schema objects. However,
if a name is longer than 30 characters or contains an u ntran slatable character, then
the short name is stored instead. To convert short nam es to full nam es, you can u se
the fun ction longname in the ut ility package DBMS_JAVA, as follows:
SQL> SELECT dbms_java.longname(object_name), ... FROM user_objects;
Table 22 describes all the colum ns in d atabase view USER_OBJECTS.
Table 22 Columns in USER_OBJECTS
Column Name Datatype Description
OBJECT_NAME VARCHAR2(128) name of object
SUBOBJECT_NAME VARCHAR2(30) nam e of any sub-object (a par tition for example)
OBJECT_ID NUMBER object number of object
Using loadjava
T bl 2 2 (C t ) C l i USER OBJECTS
8/8/2019 Java Stored
50/118
2-18 Oracle8i Java Stored Procedures Developers Guide
DATA_OBJECT_ID NUMBER object num ber of segment that contains the object
OBJECT_TYPE VARCHAR2(15) type of object (a table or ind ex for examp le)
CREATED DATE da te on which object was created
LAST_DDL_TIME DATE da te of last DDL operation on the object
TIMESTAMP VARCHAR2(19) character string containing date and time the objectwas created
STATUS VARCHAR2(7) status (valid or inv alid) of object
TEMPORARY VARCHAR2(1) indicator (y/ n) of whether current session seesonly the d ata tha t it stores in the object
GENERATED VARCHAR2(1) ind icator of wheth er nam e of the object wasgenerated by th e system
SECONDARY VARCHAR2(1) ind icator of w hether object is a second ary ob ject
created for d omain ind exes
Table 22 (Cont.) Columns in USER_OBJECTS
Column Name Datatype Description
Using dropjava
U i d j
8/8/2019 Java Stored
51/118
Loading Stored Procedures 2-19
Using dropjava
The dropjava utility converts filenames into th e nam es of schema objects, drop sthe schema objects, then deletes their digest table rows. Dropping a class invalidates
classes that d epend on it d irectly or ind irectly. Dropp ing a sou rce also drop s classes
derived from it.
On th e comman d line, you can enter the n ames of Java sou rce, class, and resource
files, SQLJ inpu t files, and un compressed JARs and ZIP archives in any order. Here
is the syntax:
dropjava {-user | -u} username/password[@database][-option_name -option_name ...] filename filename ...
where option_name stand s for the following syn tax:
{ {oci8 | o}
| {schema | S} schema_name
| {thin | t}
| {verbose | v} }
Table 23 describes the dropjava command-line options.
Table 23 dropjava Options
Option Description
oci8 Directs dropjava to communicate with the database using the OCI JDBCdr iver. This option (the default) and -thin are mu tually exclusive.
schema Drops Java schema objects from the specified schema. If this option is not
specified, then the logon schema is used.
You m ust have the DROP ANY PROCEDURE pr ivilege to d rop objects fromanother u sers schema.
thin Directs dropjava to commun icate with the d atabase using the th inJDBC driver. This option and -oci8 (the default) are mu tually exclusive.
verbose Enables verbose mode, in which progress messages are displayed.
Using dropjava
Specifying Filenames
8/8/2019 Java Stored
52/118
2-20 Oracle8i Java Stored Procedures Developers Guide
Specifying Filenamesdropjava interprets most filenames the same w ay loadjava does. With class
files, dropjava finds the name of the class in the file, then drops the corresponding
schema object. With sou rce files and SQLJ input files, dropjava finds the name of
the first class in the file, then d rops th e correspon ding schem a object. With
un compressed JARs and ZIP archives, dropjava processes the nam es of archived
files as if you had entered them on the comm and line.
If a filename has an extension other than .java, .class, .sqlj, .jar, or .zip, or
has no extension, dropjava assum es the filename is the n ame of a schema object,
then drop s all source, class, and resource schema objects with th at name. If thefilename begins w ith a slash, then dropjava prefixes ROOT to the nam e of the
schema object.
Ifdropjava encounters a filename that does not m atch the name of any schema
object, it displays an error m essage, then processes the rem aining filenames.
ExamplesIn the following example, dropjava connects to the default database using the OCI
JDBC dr iver, then drops all objects from schema BLAKE that w ere loaded from
serverObjs.jar:
> loadjava -user scott/tiger -schema BLAKE serverObjs.jar
In the next example, dropjava connects using the thin JDBC d river, then d rops a
class and resource from th e user s schema:
> loadjava -u scott/tiger@dbhost:5521:orcl -t Agent.class images.dat
Invoker Rights versus Definer Rights
Invoker Rights versus Definer Rights
8/8/2019 Java Stored
53/118
Loading Stored Procedures 2-21
Invoker Rights versus Definer Rights
By d efault, Java stored p rocedu res execute with the p rivileges of their invoker, nottheir definer. Invoker-rights procedures are not bou nd to a par ticular schema. Their
un qualified references to schema objects (such as d atabase tables) are resolved in
the schema of the invoker, not the d efiner.
To override the default behavior, specify the loadjava option definer.
Definer-rights procedu res are boun d to the schema in w hich they reside. They
execute w ith the p rivileges of their definer, and their un qua lified references to
schema objects are resolved in the schema of the d efiner.
Invoker-rights procedures let you centralize data retrieval. Consider a company that
uses a definer-rights procedu re to analyze sales. To p rovide local sales statistics, the
procedure analyze mu st access sales tables that reside at each regional site. To
do so, the procedu re mu st also reside a t each regional site. This causes a
maintenance problem.
To solve the p roblem, the company installs an inv oker-rights version of the
procedure analyze at head quarters. Now, as Figure 22shows, all regional sites
can u se the same procedu re to query their own sales tables.
Figure 22 Invoker-Rights Solution
Occasionally, you might w ant to override the default invoker-rights behavior.
Sup pose headqu arters would like the procedure analyze to calculate sales
comm issions and up date a central payroll table. That presents a p roblem because
invokers ofanalyze should not have direct access to the payroll table, wh ich
stores employee salaries and other sensitive data. As Figure 23 on page 2-22
shows, the solution is to have procedu re analyze call the definer-rights procedu re
calcComm, which, in turn, up dates the payroll table.
Schema HQSchemaWEST
analyze
sales
SchemaEAST
sales
Invoker Rights versus Definer Rights
Figure 23 Indirect Access
8/8/2019 Java S