SlideShare una empresa de Scribd logo
1 de 72
Java Training
Java in Oracle
Written by Jeff Smith
Introduction -1
Modern databases such as Oracle support Java Stored
Procedures
These slides will be geared towards Oracle Java stored
procedures, but many of the concepts would translate to
other databases as well
Java stored procedures are simply static methods of plain
old Java classes which have been loaded into Oracle and
published with a call specification (call spec).
So why write PL/SQL when you can write your stored
procedures in a beautiful language like Java, using a
powerful IDE like Eclipse? :-)
Introduction -2
Advantages of Java Stored Procedures
Java has robust type checking, so the compiler catches
many bugs for you. PL/SQL has relaxed (poor) type
checking, so many bugs don't show up until run time
Java is a true OOP language that supports and
encourages encapsulation, inheritance, interfaces, etc.
Java stored procedures can access many resources
unavailable to PL/SQL, such as EJBs, web services,
JavaMail, other external JARs, etc.
You could even have your Java stored procedure
send instant messages via AIM!
Introduction -3
Advantages of Java Stored Procedures (continued..)
Java is faster than PL/SQL for computation intensive
operations
Java can read files larger than 32k
You can develop and debug your Java stored
procedures in a slick IDE like Eclipse
Database independence--your Java stored procedures
will be portable from one database to the next
The logic in your Java stored procedures could also be
ported to a different tier in your architecture
Introduction -4
Disadvantages of Java Stored Procedures
An extra step in creating them (publishing them in
Oracle through a utility like Loadjava)
Support for database objects, types, and features is not
as complete as PL/SQL
Some data intensive operations (such as batching data
sets) is faster in PL/SQL than in Java
Slightly longer time (overhead) required to call a Java
procedure.
Bradley Brown, chief architect of TUSC, reported a
tenth of a second overhead involved in calling Java
stored procedures in Oracle 8/9
Introduction -5
This is your classic J2EE architecture
If you are starting a system from scratch,
this would be one good way to design it
O/R mapping could be JDO, Toplink,
Hibernate, or Entity beans
DAO/JDBC might work better than O/R if
you need to write complex SQL
There might be Oracle stored
procedures, but they would only deal
with data operations, not business logic
Stored procedures would probably need
to call each other, but they wouldn't need
to call business functions in the middle
tier
But what if you already have lots of
stored procedures with business logic?
Introduction -6
Java code in stateless session
beans (SSB) can call Oracle stored
procedures, but there is no way for
PL/SQL code to call Java logic in
the SSBs
So if you write a new business
function in a Java middle tier
(JBOSS), other Java code there
can access it (of course)
But what if some existing PL/SQL
code also needs to call this new
business function?
Would you have to duplicate the
function in both places?
Introduction -7
Adding Java stored
procedures to your system
doesn't require changing your
architecture
You get the benefits of writing
Java code using sound OOP
principles, and yet your
existing PL/SQL procedures
can access this new code as
easily as if it were written in
PL/SQL
Introduction -8
Java stored procedures (and functions)
can be called directly by another PL/SQL procedure or
function
can be called by Pro C
can themselves call PL/SQL stored procedures and
functions (either using JDBC/SQLExecutor or SQLJ)
can call EJBs running inside Oracle 9iAS (but not
JBOSS)
You can also write your triggers in Java
Oracle JVM-1
Oracle 8i was first version to support Java
Oracle 9i is J2SE 1.3 compatible
Starting with Oracle 9i release 2 (version 9.2), Oracle no
longer supports the Java 2 Enterprise Edition (J2EE) and
CORBA stacks in the database
Oracle has moved these capabilities to Oracle 9iAS, the
App Server version of Oracle 9. Oracle 9iAS supports EJBs,
JSPs, servlets, CORBA, etc.
Oracle JVM-2
Oracle 9i supports
Standard J2SE features
Java stored procedures
Java triggers
JDBC 2.0 (and some JDBC 3.0 support)
SQLJ
Calling out to web components, servlets, JSPs using
HTTP client
Calling out to EJBs deployed in Oracle 9iAS
JMS interface for advanced queuing systems (JMS
compatible message provider)
Oracle JVM-3
The Oracle JVM can run any Java method as a stored
procedure except for methods that instantiate a GUI
For example, the database can't create a Swing (JPanel)
window
The Oracle JVM supports
Java stored functions and procedures
Java triggers
Java database objects (general purpose)
You can either load your java classes by
using the loadjava utility
using CREATE JAVA statements
using an IDE like Oracle JDeveloper
Oracle JVM-4
Java Stored Procedures must comply with the following
rules:
No constructor
Variables and methods must be declared static
Use the default database connection (no userid/
password required, run in session)
Declare output variables as arrays pu
Java Stored Procedures can call other classes that do not
have these restrictions.
So you can write POJO classes and only the Java
stored procedure class has the restrictions listed above
Console Output (System.out)
What happens to console output from a Java Stored
Procedure?
System.out.println() statements will be written to trace
files in the Oracle UDUMP destination directory.
Alternatively, you can redirect output to a SQLPlus text
buffer (size 5000 bytes) by doing the following:
SQL> SET SERVEROUTPUT ON
SQL> EXEC dbms_java.set_output(5000);
Next call your stored procedure:
SQL> call StoredProcTest_createTable('jeff');
Your System.out.println() statements and stack traces will
appear in SQLPlus!
Create Java Function-1
You can create Java procedures and functions by typing the
Java code directly into SQLPlus or some other tool:
SQL> CREATE JAVA SOURCE NAMED "Hello" AS
public class Hello
{
public static String world()
{
return "Hello World from Java!";
}
};
/
You should get back the message "Java created".
Create Java Function-3
Next you "publish" your new Java routine by creating a call
spec. You can think of a call spec as a PL/SQL function or
procedure wrapper for your Java code. Here is an example
(typed into SQLPlus):
SQL> CREATE OR REPLACE FUNCTION hello_world return
VARCHAR2 as language java
name 'Hello.world() return java.lang.String';
You should get back the message "Function created."
Create Java Function-4
Your Java function is now available for use. To test it,
create a variable and call your stored function like so:
SQL> select hello_world() from dual;
OR
SQL> variable myString varchar2(40);
SQL> call hello_world() into :myString;
SQL> print myString;
You should get back the message "Hello world from Java!"
You can also call this stored function, hello_world, from any
PL/SQL blocks
Create Java Procedure-1
When you create a Java stored procedure, the process is
the same (instead of a function) but your call spec has a
different signature. Here is an example
create or replace procedure MyClass_createTable
(table_name IN VARCHAR2) as language java name
'mypackage.MyClass.createTable(java.lang.String)';
/
Note that this example illustrates how to create a call spec
for a class that resides in a package (mypackage)
Java Compile Error Debug Tip
If you get a message like "Warning: Java created with
compilation errors", you can determine the cause of the
error like so:
SQL> select * from user_errors
Call Spec Tip-1
You'll confuse Oracle if you give your stored procedure the
same name as your class--it needs to be different.
So when you create your Java stored procedure, use the
following naming convention when creating your call spec.
For example
CREATE OR REPLACE FUNCTION classname_methodname return
VARCHAR2 as language java
name 'Classname.methodname() return java.lang.String';
Here is our Hello world example:
CREATE OR REPLACE FUNCTION hello_world return
VARCHAR2 as language java
name 'Hello.world() return java.lang.String';
Call Spec Tip-2
Java stored procedures can follow the same notation. For
example, the following call spec is for a class named
com.cexp.StoredProcTest with a method named
createTable that takes a single (String) parameter:
CREATE OR REPLACE PROCEDURE
StoredProcTest_createTable(table_name IN VARCHAR2) AS
language java name
'com.cexp.StoredProcTest.createTable(java.lang.String)';
Review
Why would you choose to use Java stored procedures
instead of PL/SQL?
Why would you choose to use PL/SQL?
Why might you use Java stored procedures instead of
writing your Java business logic in a J2EE container (middle
tier)?
What is a call spec?
How can you view the output of System.out.println()
statements?
Create Java Class Using Bfile-1
Instead of typing the Java class directly into a tool like
SQLPlus, you probably would prefer to compile and test the
class using another tool (perhaps Eclipse) and just load it
into the database
First you need to declare the directory in Oracle.
If Oracle is running from a UNIX server, you need to specify
a directory on that server (not your C: drive). For example,
you can type the following into SQLPlus
SQL> create or replace directory MyDir as
'/home/jesmith';
You should get back the message "Directory created."
Create Java Class Using Bfile-2
Once you have defined the directory in Oracle, you can
create the Java class in Oracle by typing the following into
SQLPlus
SQL> create or replace java class using bfile (MyDir,
'Hello.class');
/
You should get back the message "Java created."
You can delete your directory now that we are finished with
it:
drop directory MyDir;
Create Java Class Using Bfile-3
Next, create your call spec for the stored function:
SQL> CREATE OR REPLACE FUNCTION hello_world return
VARCHAR2 as language java
name 'Hello.world() return java.lang.String';
Your Java function (created from the binary file) is now
available for use.
You can request that Oracle describe your call spec like so:
SQL> desc hello_world;
Oracle returns:
FUNCTION hello_world RETURNS VARCHAR2
Create Java Class Using Bfile-4
Your Java stored function (created from the binary file) is
now available for use. To test it, type the following into
SQLPlus
SQL> select hello_world() from dual;
OR
SQL> variable myString varchar2(40);
SQL> call hello_world() into :myString;
SQL> print myString;
Note that you can also call your stored function from any
other PL/SQL procedure or function.
Which Classes Are Loaded? -1
You can determine which Java "system" classes are
currently loaded in Oracle by selecting from the
dba_objects table.
To determine which "user" classes are loaded, you can
select from the user_objects table. For example, to
determine the class name, created date, and status of your
Java classes loaded in Oracle:
select OBJECT_NAME, CREATED, STATUS
from user_objects
where object_type = 'JAVA CLASS'
Note: classes with status "invalid" aren't necessarily invalid,
they just haven't been compiled in Oracle yet.
Which Classes Are Loaded? -2
If you use Toad, you can click on the Java tab of the
schema browser to see which classes are loaded.
In Toad, you can right-click on one of these classes and
select "compile".
If Oracle likes your class, you'll see the message,
"Compiled without errors".
If Oracle has rejected your class, you'll get an error
message about why Oracle rejected it.
(see next slide)
Viewing Java Classes With Toad
Viewing Java classes in a schema and compiling
Loadjava Utility-1
Instead of using a tool like SQLPlus to load your Java class
into Oracle, you might prefer using a command line tool like
the loadjava utility
This tool exists on the Oracle server in the
$ORACLE_HOME/bin directory
So if Oracle is installed on a UNIX server, the tool will reside
on that server (not the Oracle client directory on a user's
Windows machine).
You can also run loadjava from an application like SQLPlus
by calling sys.dbms_java.loadjava(...)
Loadjava Utility-2
Loadjava loads Java source files, classes, JAR files, and
other resources into the database where they are stored as
Java schema objects
Note: In Toad, you can find these Java schema objects
on the Java tab of the Schema Browser window
Loadjava Utility-3
With Oracle 9i (version 9.2), loadjava allows you to
automatically publish Java classes as stored procedures by
creating the corresponding call specs for methods
contained in the processed classes
With Oracle 8i, you have to create the call spec
(procedure or function) yourself
Loadjava Utility-4
According to Oracle, the Loadjava syntax is (assumes
loadjava.bat is installed in the Oracle Home directory and
the HelloWorld.class file is in the current directory of the
same server)
loadjava -user schema/password HelloWorld.class
or
loadjava -user schema/password HelloWorld.java
I got an Oracle error with the syntax above. To load a java
file to wdevprja on snowmass, I had to use
loadjava -force -user
wdevprja/wdevprja@snowmass:1521:wdev -thin
MyClass.java
Loadjava Utility-5
You can also execute this from SQLPlus like so:
SQL> host loadjava -force -user
wdevprja/mypassword@snowmass:1521:wdev
-thin MyClass.java
To load a jar file into wdevcnv (Oracle 9.2), you log into
snowmass as user wdevcnv and
loadjava -force -user
wdevcnv/mypassword@snowmass:1526:wdevcnv -thin
SQLExecutorFramework.jar
Loadjava Utility-6
You can also use the sys.dbms_java.loadjava function in
SQLPlus to load your Java class
SQL>call sys.dbms_java.loadjava('-v -r -grant PUBLIC
-synonym HelloWorld.java');
This example would load the class HelloWorld into the
schema you logged into
Class Resolver-1
The Oracle JVM uses a resolver to search for supporting
classes when you call a method in the HelloWorld class.
A supporting class is just a class that is referenced by
your class. For example, if your class uses String
objects, then the String class is a "supporting class"
Oracle provides a default class resolver which searches the
current schema and then PUBLIC
PUBLIC classes include all the standard JDK classes
If you want to access classes defined in another schema,
you specify this other resolver on the loadjava command
line
Class Resolver-2
If you want to access classes defined in another schema,
you specify this other resolver on the loadjava command
line
The following example uses a custom resolver spec which
includes the SCHEMA1 schema, SCHEMA2 schema, and
PUBLIC
loadjava -resolve -resolver
"((* SCHEMA1)(* SCHEMA2)(* PUBLIC))"
This command would search SCHEMA1, SCHEMA2, and
PUBLIC to resolve all class references in your code
Class Resolver-3
You can also narrow the resolver spec to search for a
subset of classes within a schema:
loadjava -resolve -resolver
'(("com/cexp/*" SCHEMA1)(* SCHEMA2)(* PUBLIC))'
This command would search all classes whose package
name begins with com.cexp in SCHEMA1, all classes in
SCHEMA2, and all PUBLIC classes
Compiling Classes In Oracle-1
You may be surprised to see that after you've loaded your
classes into Oracle with the LoadJava utility, they are
uncompiled (status "invalid").
Don't worry! Your classes will either be compiled
automatically on first use or you can manually compile them
yourself in a tool like SQLPlus:
SQL> ALTER JAVA CLASS "com.cexp.wms.MyClass" RESOLVE;
or
SQL> ALTER JAVA SOURCE "com.cexp.wms.MyClass" COMPILE;
You can also compile them in Toad (see next slide)
Compiling Classes In Oracle-2
Here is Oracle's easy to understand diagram of Alter Java...
ALTER JAVA SOURCE - used to compile a Java source
ALTER JAVA CLASS - used to resolve (find classes
referenced) a Java class
ALTER JAVA CLASS "Agent" RESOLVER (("/home/java/bin/*"
pm)(* public)) RESOLVE;
Compiling Classes In Oracle-3
The invoker_rights_clause lets you specify whether the
methods of the class execute with the privileges and in the
schema of the user who defined it or with the privileges and
in the schema of CURRENT_USER.
It also determines how Oracle resolves external names in
queries, DML operations, and dynamic SQL statements in
the member functions and procedures of the type.
Specify CURRENT_USER if you want the methods of
the class to execute with the privileges of
CURRENT_USER. This clause is the default and
creates an "invoker-rights class."
Specify DEFINER if you want the methods of the class
to execute with the privileges of the user who defined it.
Granting Permissions-1
Sometimes you will need to grant the Oracle JVM
permissions in order for your Java stored procedure (or
trigger) to function
For example, if your Java class reads or writes from disk,
you may need to grant the Oracle JVM certain file system
permissions. For example:
EXEC dbms_Java.Grant_Permission('wdevcnv',
'java.io.FilePermission', '<<ALL FILES>>', 'read,
write, execute, delete');
where 'wdevcnv' is the schema name)
For an example of exporting the contents of a BLOB
datatype to the file system, see:
http://www.oracle-base.com/Articles/8i/ExportBlob.asp
Loading JAR files
To load a JAR file into an Oracle 8.1.7 server named
wdev.snowmass with user wdevprja on the standard port
1521, you could type the following in SQLPlus
SQL> host loadjava -force -user
wdevprja/mypassword@snowmass:1521:wdev
-thin MyProject.jar
(this command assumes that MyProject.jar is in the current
directory)
Compiling JARs With Toad
Once you load your JAR file in Oracle 8.1.7, you'll need to
compile the classes. Using a tool like Toad makes this easy
Loadjava Summary
The only drawback of loadjava is that it only works on the
operating system on which Oracle resides. It also requires
you to manually create a call spec.
To recap, if you are developing your Java code on Windows
and Oracle resides elsewhere (perhaps on UNIX), you need
to do the following
first copy the file somewhere on the UNIX box
(perhaps via FTP)
next call the loadjava utility
next create a call spec (function or procedure)
This is rather tedious. Ideally, we would find a tool that
automates this whole process for us.
Loadjava And Toad-1
You can use Toad to load Java classes into Oracle (it uses
the loadjava utility). Go to the Tools Menu, Java Manager
option. It must be able to find loadjava.bat in order to work.
Drop Java Source/Class-1
You may want to drop a source file or class you've loaded
into Oracle. Use the drop java source or drop java class
command to do this. For example:
SQL> drop java source "HelloWorld";
SQL> drop java source "com.cexp.wms.oracle.HelloWorld"
SQL> drop java class "HelloWorld";
To drop your function (call spec) named HelloWorld:
SQL> drop function hello_world;
Toad makes it easy to drop classes and sources. Just go to
the Java tab of the schema browser, right click on the
object you want to drop, select "drop object".
You can also drop the function on the Procs tab
Drop Java Source/Class-2
You can also use the dropjava command line utility
(installed on the same server as the database). For
example:
dropjava -u username/password myPackage.myClass
dropjava -u username/password myJar.jar
Exercise
Using SQLPlus, create a test table in wdevprja called something like
"MyName_Test". The table should have the following fields: EMPID
(Number), FNAME (VARCHAR2) and LName (VARCHAR2). Put a
couple records in it.
Using Eclipse, create a Java stored procedure in package
com.cexp.wms.oracle. Your class should be called
"MyName_StoredProcTest" and your method should be called
"insertRecord(String firstName, lastName)". This stored procedure can
use standard JDBC or the SQLExecutor framework to insert records
into your table.
Load your Java stored procedure into the database and create a call
spec for it. SQLPlus commands may be the easiest way to do this.
Test your stored procedure by calling it from SQLPlus. Redirect
System.out.println() output to the SQLPlus window to aid in debugging.
Remember to drop your table when you are done. Also drop your Java
stored procedure and your call spec.
Problems Loading Java-1
Occasionally, one of your class files may compile fine with
Sun JDK 1.3, but be rejected by Oracle.
For example, one of the classes in my
SQLExecutorFramework.jar file was rejected by Oracle
because a function returned its value in a finally block
(see next slide)
Problems Loading Java-2
static int getDbType(Connection con)
{
try
{
....
}
catch (SQLException e)
{
....
}
finally
{
return(dbType);
}
}
Problems Loading Java-3
When I compiled this class in Toad (go to Java tab of
Schema browser and right click on Java classname), I got
the following error from Oracle:
JAVA CLASS WDEVPRJA.com/cexp/wms/jdbc/DatabaseType
On line: 0
ORA-29545: badly formed class: at offset 78 of
com.cexp.wms.jdbc.DatabaseType.getDbType return type
is inconsistent with return opcode
Problems Loading Java-4
When I compiled this class in Toad (go to Java tab of
Schema browser and right click on Java classname), I got
the following error from Oracle:
JAVA CLASS WDEVPRJA.com/cexp/wms/jdbc/DatabaseType
On line: 0
ORA-29545: badly formed class: at offset 78 of
com.cexp.wms.jdbc.DatabaseType.getDbType return type
is inconsistent with return opcode
Problems Loading Java-5
When I rewrote my code like this, Oracle was happy:
static int getDbType(Connection con)
{
try
{
....
}
catch (SQLException e)
{
....
}
return(dbType);
}
Problems Loading Java-6
The new code is probably better, so it was an easy decision
to make the code change
SQLExecutorFramework.jar now works in Oracle 8.1.7
The point here is that there may be times your Java classes
are rejected by Oracle when you try to load them
Use a tool like Toad to get the compile error from Oracle
and then fix your classes accordingly
Problems Using LoadJava-1
There is a bug in Oracle 8 that occurs when you use
loadjava to re-load an already loaded CLASS file. Oracle
seems to get confused and doesn't recompile the new class
file correctly. Loading the .java (source) instead of the class
file seems to work every time:
host loadjava -force -user
wdevprja/wdevprja@snowmass:1521:wdev -thin
JeffStoredProcTest.java
I don't know if this is a problem in Oracle 9.2 or not. To be
safe, I'd recommend loading Java source files instead of
class files (since Oracle has to recompile them anyway).
Problems Using LoadJava-2
You can load a JAR file into Oracle with a single loadjava
command:
loadjava -force -user
wdevprja/password@snowmass:1521:wdev -thin
SQLExecutorFramework.jar
Occasionally, a class in your JAR file might not get loaded
into Oracle (version 8 at least). When you try to compile
another class which uses this missing JAR file class, you'll
get a compile error.
My advice is to check that each class in your JAR is loaded
into Oracle
Problems Compiling/Running-1
If you ever get an error message like this:
The following error has occurred:
ORA-29549: class WDEVPRJA.com/cexp/wms/oracle/StoredProcTest has
changed, Java session state cleared
ORA-06512: at "WDEVPRJA.STOREDPROCTEST_CREATETABLE", line0
ORA-06512: at line 2
The Oracle docs say "Cause: A class in use by the current
session was redefined or dropped, invalidating the current
Java session state and requiring that it be cleared."
It means that you've reloaded a Java class in Oracle and
the new version is different (and needs to be recompiled)
Just ignore this error and re-run the stored procedure. The
error should go away on the 2nd attempt
Problems Debugging-1
To view System.out.println in SQLPlus, you'll need to:
set serveroutput on
call dbms_java.set_output(5000);
(Note: I had to execute this before EACH call to my
stored procedure)
If a runtime exception is thrown, you may not see any of
your System.out.println statements (that preceded the
runtime exception) at all!
Problems Setting Query Timeout
When I set a query timeout in a Java stored procedure like
so:
prepStatement.setQueryTimeout(15);
prepStatement.executeUpdate(); //null pointer exception
I got a NullPointerException when the executeUpdate()
statement executed.
Hence, I don't recommend setting a query timeout :-)
Creating a Java Trigger-1
You can also write your Oracle triggers in Java. For
example, you could write the following trigger class:
import java.sql.*;
public class EmployeeInsertTrigger
{
public static void onInsert(Connection con,
Long[] newid)
{
Long NextSeqValue = new Long(0); //def to zero
Creating a Java Trigger-2
try
{
//Get next id from the sequence
String sql = "select emp_seq.nextval from dual";
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next ())
NextSeqValue = new Long(rs.getLong(1));
newid[0] = NextSeqValue;
// Close the Statement stmt.close();
ps.close();
} catch(SQLException e) {}
}
}
Creating a Java Trigger-3
Next, compile your Java class and then load it into the
database:
CREATE OR REPLACE JAVA CLASS USING BFILE (MyFolder,
'EmployeeInsertTrigger.class');
/
Next you create your call spec:
CREATE OR REPLACE PROCEDURE
EMPLOYEE_INSERT( NEWID IN OUT NUMBER )
AS LANGUAGE JAVA NAME
'EmployeeInsertTrigger.onInsert( java.sql.Connection,
java.lang.Long[])';
/
Creating a Java Trigger-4
Finally, create your trigger which will fire before each insert
into the Employee table:
CREATE OR REPLACE TRIGGER EMPLOYEE_BEF_INS_TRG
BEFORE INSERT ON EMPLOYEE FOR EACH ROW
EMPLOYEE_INSERT( new.EMPLOYEE_ID );
/
That's all there is to it!
My Loadjava Utility-1
I've written a utility called JavaLoader which replaces the
Oracle version. My LoadJava program (written in Java, of
course) automates the whole process.
Copies your class file to the UNIX server hosting Oracle
Creates an Oracle directory alias
Creates the Java class in Oracle using the "CREATE
JAVA CLASS USING BFILE" command
Creates the corresponding call spec
Compiles the Java class in Oracle
Deletes the temporary class file from the UNIX server
My Loadjava Utility-2
JavaLoader uses a properties file to store the information
required to perform all these tasks
You can edit the "template" javaloader.properties file to load
your own, custom Java classes
My Loadjava Utility-3
# Properties for Jeff Smith's Load Java Program
ftp.servername=uscobrmfa-ub-14.cexp.com
ftp.username=jesmith
oracle.connurl=jdbc:oracle:thin:@SNOWMASS:1521:WDEVCNV
oracle.username=wdevcnv
oracle.password=wdevcnv
java.classname=StoredProcTest.class
java.package=com.cexp.wms.oracle
java.methodname=createTable
My Loadjava Utility-4
#STORED PROCEDURE EXAMPLE (ORACLE CALL SPEC)
cs0=CREATE OR REPLACE PROCEDURE
cs1=StoredProcTest_createTable(table_name IN VARCHAR2) AS language java
cs2=NAME 'com.cexp.wms.oracle.StoredProcTest.createTable(java.lang.String)'
cs3=
cs4=
cs5=
#STORED FUNCTION EXAMPLE (ORACLE CALL SPEC)
#cs0=CREATE OR REPLACE FUNCTION StoredProcTest_getFullName(fname IN
#cs1=VARCHAR2, lname IN VARCHAR2)
#cs2=return VARCHAR2 AS language java
#cs3= NAME 'com.cexp.wms.oracle.StoredProcTest.getFullName(java.lang.String,
#cs4=java.lang.String) return java.lang.String'
#cs5=
My Loadjava Utility-5
Syntax: Javaloader [password] [optional: properties filename].
If you leave the properties filename blank, the name
"javaloader.properties" is assumed (similar to the way Ant
assumes a file called build.xml will exist)
Example: javaloader mypassword
Example: javaloader mypassword javaloader.properties
My Loadjava Utility-6
For more information and to download the utility, see:
http://expressway2.cexp.com/info_services/D&L_Systems/java/
JavaLoader.htm
A Look Into The Crystal Ball
Given the rising popularity of Java, Oracle will likely migrate
the database in that direction. While PL/SQL support won't
be going away, new development at Oracle will probably
focus on Java stored procedures, functions and triggers
Other databases are also moving in the direction of Java
Postgres supports Java stored procedures (PL/PGJ)
MySQL may follow suit
But you probably won't see Microsoft add Java stored
procedures to SQL Server before hell freezes over!
Resources
Oracle's Java Stored Procedure Samples:
http://technet.oracle.com/sample_code/tech/java/jsp/oracle9ijsp.html

Más contenido relacionado

La actualidad más candente

La actualidad más candente (20)

まだ DOM 操作で消耗してるの?
まだ DOM 操作で消耗してるの?まだ DOM 操作で消耗してるの?
まだ DOM 操作で消耗してるの?
 
Api types
Api typesApi types
Api types
 
ASP.NET Core: The best of the new bits
ASP.NET Core: The best of the new bitsASP.NET Core: The best of the new bits
ASP.NET Core: The best of the new bits
 
Securing Your API
Securing Your APISecuring Your API
Securing Your API
 
Load Testing and JMeter Presentation
Load Testing and JMeter PresentationLoad Testing and JMeter Presentation
Load Testing and JMeter Presentation
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
 
iOS Application Pentesting
iOS Application PentestingiOS Application Pentesting
iOS Application Pentesting
 
What is an API?
What is an API?What is an API?
What is an API?
 
flutter intro.pptx
flutter intro.pptxflutter intro.pptx
flutter intro.pptx
 
Understand front end developer
Understand front end developerUnderstand front end developer
Understand front end developer
 
Api security-testing
Api security-testingApi security-testing
Api security-testing
 
REST & RESTful Web Services
REST & RESTful Web ServicesREST & RESTful Web Services
REST & RESTful Web Services
 
SQL Injections (Part 1)
SQL Injections (Part 1)SQL Injections (Part 1)
SQL Injections (Part 1)
 
gRPC on .NET Core - NDC Sydney 2019
gRPC on .NET Core - NDC Sydney 2019gRPC on .NET Core - NDC Sydney 2019
gRPC on .NET Core - NDC Sydney 2019
 
Documenting your REST API with Swagger - JOIN 2014
Documenting your REST API with Swagger - JOIN 2014Documenting your REST API with Swagger - JOIN 2014
Documenting your REST API with Swagger - JOIN 2014
 
Best Practices for RESTful Web Services
Best Practices for RESTful Web ServicesBest Practices for RESTful Web Services
Best Practices for RESTful Web Services
 
Application Performance Monitoring (APM)
Application Performance Monitoring (APM)Application Performance Monitoring (APM)
Application Performance Monitoring (APM)
 
New relic
New relicNew relic
New relic
 
Modern API Security with JSON Web Tokens
Modern API Security with JSON Web TokensModern API Security with JSON Web Tokens
Modern API Security with JSON Web Tokens
 
React native
React nativeReact native
React native
 

Similar a 13 java in oracle

Improving the Performance of PL/SQL function calls from SQL
Improving the Performance of PL/SQL function calls from SQLImproving the Performance of PL/SQL function calls from SQL
Improving the Performance of PL/SQL function calls from SQLGuatemala User Group
 
Writing Stored Procedures in Oracle RDBMS
Writing Stored Procedures in Oracle RDBMSWriting Stored Procedures in Oracle RDBMS
Writing Stored Procedures in Oracle RDBMSMartin Toshev
 
Writing Java Stored Procedures in Oracle 12c
Writing Java Stored Procedures in Oracle 12cWriting Java Stored Procedures in Oracle 12c
Writing Java Stored Procedures in Oracle 12cMartin Toshev
 
Writing Stored Procedures with Oracle Database 12c
Writing Stored Procedures with Oracle Database 12cWriting Stored Procedures with Oracle Database 12c
Writing Stored Procedures with Oracle Database 12cMartin Toshev
 
Advanced_SQL_ISASasASasaASnjection (1).ppt
Advanced_SQL_ISASasASasaASnjection (1).pptAdvanced_SQL_ISASasASasaASnjection (1).ppt
Advanced_SQL_ISASasASasaASnjection (1).pptssuserde23af
 
New and improved hacking oracle from web apps sumit sidharth
New and improved hacking oracle from web apps   sumit sidharthNew and improved hacking oracle from web apps   sumit sidharth
New and improved hacking oracle from web apps sumit sidharthowaspindia
 
Java 9 / Jigsaw - AJUG/VJUG session
Java 9 / Jigsaw - AJUG/VJUG  sessionJava 9 / Jigsaw - AJUG/VJUG  session
Java 9 / Jigsaw - AJUG/VJUG sessionMani Sarkar
 
Database design i_-_1_dl300
Database design i_-_1_dl300Database design i_-_1_dl300
Database design i_-_1_dl300KOI Lastone
 
EJB 3.0 Java Persistence with Oracle TopLink
EJB 3.0 Java Persistence with Oracle TopLinkEJB 3.0 Java Persistence with Oracle TopLink
EJB 3.0 Java Persistence with Oracle TopLinkBill Lyons
 
Unit of competency
Unit of competencyUnit of competency
Unit of competencyloidasacueza
 
Oracle PL/SQL online training | PL/SQL online Training
Oracle PL/SQL online training | PL/SQL online TrainingOracle PL/SQL online training | PL/SQL online Training
Oracle PL/SQL online training | PL/SQL online Trainingsuresh
 
PL/SQL Interview Questions
PL/SQL Interview QuestionsPL/SQL Interview Questions
PL/SQL Interview QuestionsSrinimf-Slides
 
Oracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAsOracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAsAlex Zaballa
 

Similar a 13 java in oracle (20)

Improving the Performance of PL/SQL function calls from SQL
Improving the Performance of PL/SQL function calls from SQLImproving the Performance of PL/SQL function calls from SQL
Improving the Performance of PL/SQL function calls from SQL
 
Writing Stored Procedures in Oracle RDBMS
Writing Stored Procedures in Oracle RDBMSWriting Stored Procedures in Oracle RDBMS
Writing Stored Procedures in Oracle RDBMS
 
PHP Oracle
PHP OraclePHP Oracle
PHP Oracle
 
Writing Java Stored Procedures in Oracle 12c
Writing Java Stored Procedures in Oracle 12cWriting Java Stored Procedures in Oracle 12c
Writing Java Stored Procedures in Oracle 12c
 
Java platform
Java platformJava platform
Java platform
 
Writing Stored Procedures with Oracle Database 12c
Writing Stored Procedures with Oracle Database 12cWriting Stored Procedures with Oracle Database 12c
Writing Stored Procedures with Oracle Database 12c
 
Java 9 Features
Java 9 FeaturesJava 9 Features
Java 9 Features
 
Panama.pdf
Panama.pdfPanama.pdf
Panama.pdf
 
Advanced_SQL_ISASasASasaASnjection (1).ppt
Advanced_SQL_ISASasASasaASnjection (1).pptAdvanced_SQL_ISASasASasaASnjection (1).ppt
Advanced_SQL_ISASasASasaASnjection (1).ppt
 
Java 9
Java 9Java 9
Java 9
 
New and improved hacking oracle from web apps sumit sidharth
New and improved hacking oracle from web apps   sumit sidharthNew and improved hacking oracle from web apps   sumit sidharth
New and improved hacking oracle from web apps sumit sidharth
 
Pl sql chapter 1
Pl sql chapter 1Pl sql chapter 1
Pl sql chapter 1
 
Java 9 / Jigsaw - AJUG/VJUG session
Java 9 / Jigsaw - AJUG/VJUG  sessionJava 9 / Jigsaw - AJUG/VJUG  session
Java 9 / Jigsaw - AJUG/VJUG session
 
Database design i_-_1_dl300
Database design i_-_1_dl300Database design i_-_1_dl300
Database design i_-_1_dl300
 
EJB 3.0 Java Persistence with Oracle TopLink
EJB 3.0 Java Persistence with Oracle TopLinkEJB 3.0 Java Persistence with Oracle TopLink
EJB 3.0 Java Persistence with Oracle TopLink
 
4 jdbc step1
4 jdbc step14 jdbc step1
4 jdbc step1
 
Unit of competency
Unit of competencyUnit of competency
Unit of competency
 
Oracle PL/SQL online training | PL/SQL online Training
Oracle PL/SQL online training | PL/SQL online TrainingOracle PL/SQL online training | PL/SQL online Training
Oracle PL/SQL online training | PL/SQL online Training
 
PL/SQL Interview Questions
PL/SQL Interview QuestionsPL/SQL Interview Questions
PL/SQL Interview Questions
 
Oracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAsOracle Database 12c - New Features for Developers and DBAs
Oracle Database 12c - New Features for Developers and DBAs
 

Más de Graham Royce (20)

Chapter 18
Chapter 18Chapter 18
Chapter 18
 
Chapter 17
Chapter 17Chapter 17
Chapter 17
 
Chapter 16
Chapter 16Chapter 16
Chapter 16
 
Chapter 15
Chapter 15Chapter 15
Chapter 15
 
Chapter 14
Chapter 14Chapter 14
Chapter 14
 
Chapter 13
Chapter 13Chapter 13
Chapter 13
 
Chapter 12
Chapter 12Chapter 12
Chapter 12
 
Chapter 11
Chapter 11Chapter 11
Chapter 11
 
Chapter 10
Chapter 10Chapter 10
Chapter 10
 
Chapter 09
Chapter 09Chapter 09
Chapter 09
 
Chapter 08
Chapter 08Chapter 08
Chapter 08
 
Chapter 07
Chapter 07Chapter 07
Chapter 07
 
Chapter 06
Chapter 06Chapter 06
Chapter 06
 
Chapter 05
Chapter 05Chapter 05
Chapter 05
 
Chapter 04
Chapter 04Chapter 04
Chapter 04
 
Chapter 03
Chapter 03Chapter 03
Chapter 03
 
Chapter 02
Chapter 02Chapter 02
Chapter 02
 
Chapter 01
Chapter 01Chapter 01
Chapter 01
 
Java tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo CahersiveenJava tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo Cahersiveen
 
My 3 min pitch pack
My 3 min pitch packMy 3 min pitch pack
My 3 min pitch pack
 

Último

Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusZilliz
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 

Último (20)

Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 

13 java in oracle

  • 1. Java Training Java in Oracle Written by Jeff Smith
  • 2. Introduction -1 Modern databases such as Oracle support Java Stored Procedures These slides will be geared towards Oracle Java stored procedures, but many of the concepts would translate to other databases as well Java stored procedures are simply static methods of plain old Java classes which have been loaded into Oracle and published with a call specification (call spec). So why write PL/SQL when you can write your stored procedures in a beautiful language like Java, using a powerful IDE like Eclipse? :-)
  • 3. Introduction -2 Advantages of Java Stored Procedures Java has robust type checking, so the compiler catches many bugs for you. PL/SQL has relaxed (poor) type checking, so many bugs don't show up until run time Java is a true OOP language that supports and encourages encapsulation, inheritance, interfaces, etc. Java stored procedures can access many resources unavailable to PL/SQL, such as EJBs, web services, JavaMail, other external JARs, etc. You could even have your Java stored procedure send instant messages via AIM!
  • 4. Introduction -3 Advantages of Java Stored Procedures (continued..) Java is faster than PL/SQL for computation intensive operations Java can read files larger than 32k You can develop and debug your Java stored procedures in a slick IDE like Eclipse Database independence--your Java stored procedures will be portable from one database to the next The logic in your Java stored procedures could also be ported to a different tier in your architecture
  • 5. Introduction -4 Disadvantages of Java Stored Procedures An extra step in creating them (publishing them in Oracle through a utility like Loadjava) Support for database objects, types, and features is not as complete as PL/SQL Some data intensive operations (such as batching data sets) is faster in PL/SQL than in Java Slightly longer time (overhead) required to call a Java procedure. Bradley Brown, chief architect of TUSC, reported a tenth of a second overhead involved in calling Java stored procedures in Oracle 8/9
  • 6. Introduction -5 This is your classic J2EE architecture If you are starting a system from scratch, this would be one good way to design it O/R mapping could be JDO, Toplink, Hibernate, or Entity beans DAO/JDBC might work better than O/R if you need to write complex SQL There might be Oracle stored procedures, but they would only deal with data operations, not business logic Stored procedures would probably need to call each other, but they wouldn't need to call business functions in the middle tier But what if you already have lots of stored procedures with business logic?
  • 7. Introduction -6 Java code in stateless session beans (SSB) can call Oracle stored procedures, but there is no way for PL/SQL code to call Java logic in the SSBs So if you write a new business function in a Java middle tier (JBOSS), other Java code there can access it (of course) But what if some existing PL/SQL code also needs to call this new business function? Would you have to duplicate the function in both places?
  • 8. Introduction -7 Adding Java stored procedures to your system doesn't require changing your architecture You get the benefits of writing Java code using sound OOP principles, and yet your existing PL/SQL procedures can access this new code as easily as if it were written in PL/SQL
  • 9. Introduction -8 Java stored procedures (and functions) can be called directly by another PL/SQL procedure or function can be called by Pro C can themselves call PL/SQL stored procedures and functions (either using JDBC/SQLExecutor or SQLJ) can call EJBs running inside Oracle 9iAS (but not JBOSS) You can also write your triggers in Java
  • 10. Oracle JVM-1 Oracle 8i was first version to support Java Oracle 9i is J2SE 1.3 compatible Starting with Oracle 9i release 2 (version 9.2), Oracle no longer supports the Java 2 Enterprise Edition (J2EE) and CORBA stacks in the database Oracle has moved these capabilities to Oracle 9iAS, the App Server version of Oracle 9. Oracle 9iAS supports EJBs, JSPs, servlets, CORBA, etc.
  • 11. Oracle JVM-2 Oracle 9i supports Standard J2SE features Java stored procedures Java triggers JDBC 2.0 (and some JDBC 3.0 support) SQLJ Calling out to web components, servlets, JSPs using HTTP client Calling out to EJBs deployed in Oracle 9iAS JMS interface for advanced queuing systems (JMS compatible message provider)
  • 12. Oracle JVM-3 The Oracle JVM can run any Java method as a stored procedure except for methods that instantiate a GUI For example, the database can't create a Swing (JPanel) window The Oracle JVM supports Java stored functions and procedures Java triggers Java database objects (general purpose) You can either load your java classes by using the loadjava utility using CREATE JAVA statements using an IDE like Oracle JDeveloper
  • 13. Oracle JVM-4 Java Stored Procedures must comply with the following rules: No constructor Variables and methods must be declared static Use the default database connection (no userid/ password required, run in session) Declare output variables as arrays pu Java Stored Procedures can call other classes that do not have these restrictions. So you can write POJO classes and only the Java stored procedure class has the restrictions listed above
  • 14. Console Output (System.out) What happens to console output from a Java Stored Procedure? System.out.println() statements will be written to trace files in the Oracle UDUMP destination directory. Alternatively, you can redirect output to a SQLPlus text buffer (size 5000 bytes) by doing the following: SQL> SET SERVEROUTPUT ON SQL> EXEC dbms_java.set_output(5000); Next call your stored procedure: SQL> call StoredProcTest_createTable('jeff'); Your System.out.println() statements and stack traces will appear in SQLPlus!
  • 15. Create Java Function-1 You can create Java procedures and functions by typing the Java code directly into SQLPlus or some other tool: SQL> CREATE JAVA SOURCE NAMED "Hello" AS public class Hello { public static String world() { return "Hello World from Java!"; } }; / You should get back the message "Java created".
  • 16. Create Java Function-3 Next you "publish" your new Java routine by creating a call spec. You can think of a call spec as a PL/SQL function or procedure wrapper for your Java code. Here is an example (typed into SQLPlus): SQL> CREATE OR REPLACE FUNCTION hello_world return VARCHAR2 as language java name 'Hello.world() return java.lang.String'; You should get back the message "Function created."
  • 17. Create Java Function-4 Your Java function is now available for use. To test it, create a variable and call your stored function like so: SQL> select hello_world() from dual; OR SQL> variable myString varchar2(40); SQL> call hello_world() into :myString; SQL> print myString; You should get back the message "Hello world from Java!" You can also call this stored function, hello_world, from any PL/SQL blocks
  • 18. Create Java Procedure-1 When you create a Java stored procedure, the process is the same (instead of a function) but your call spec has a different signature. Here is an example create or replace procedure MyClass_createTable (table_name IN VARCHAR2) as language java name 'mypackage.MyClass.createTable(java.lang.String)'; / Note that this example illustrates how to create a call spec for a class that resides in a package (mypackage)
  • 19. Java Compile Error Debug Tip If you get a message like "Warning: Java created with compilation errors", you can determine the cause of the error like so: SQL> select * from user_errors
  • 20. Call Spec Tip-1 You'll confuse Oracle if you give your stored procedure the same name as your class--it needs to be different. So when you create your Java stored procedure, use the following naming convention when creating your call spec. For example CREATE OR REPLACE FUNCTION classname_methodname return VARCHAR2 as language java name 'Classname.methodname() return java.lang.String'; Here is our Hello world example: CREATE OR REPLACE FUNCTION hello_world return VARCHAR2 as language java name 'Hello.world() return java.lang.String';
  • 21. Call Spec Tip-2 Java stored procedures can follow the same notation. For example, the following call spec is for a class named com.cexp.StoredProcTest with a method named createTable that takes a single (String) parameter: CREATE OR REPLACE PROCEDURE StoredProcTest_createTable(table_name IN VARCHAR2) AS language java name 'com.cexp.StoredProcTest.createTable(java.lang.String)';
  • 22. Review Why would you choose to use Java stored procedures instead of PL/SQL? Why would you choose to use PL/SQL? Why might you use Java stored procedures instead of writing your Java business logic in a J2EE container (middle tier)? What is a call spec? How can you view the output of System.out.println() statements?
  • 23. Create Java Class Using Bfile-1 Instead of typing the Java class directly into a tool like SQLPlus, you probably would prefer to compile and test the class using another tool (perhaps Eclipse) and just load it into the database First you need to declare the directory in Oracle. If Oracle is running from a UNIX server, you need to specify a directory on that server (not your C: drive). For example, you can type the following into SQLPlus SQL> create or replace directory MyDir as '/home/jesmith'; You should get back the message "Directory created."
  • 24. Create Java Class Using Bfile-2 Once you have defined the directory in Oracle, you can create the Java class in Oracle by typing the following into SQLPlus SQL> create or replace java class using bfile (MyDir, 'Hello.class'); / You should get back the message "Java created." You can delete your directory now that we are finished with it: drop directory MyDir;
  • 25. Create Java Class Using Bfile-3 Next, create your call spec for the stored function: SQL> CREATE OR REPLACE FUNCTION hello_world return VARCHAR2 as language java name 'Hello.world() return java.lang.String'; Your Java function (created from the binary file) is now available for use. You can request that Oracle describe your call spec like so: SQL> desc hello_world; Oracle returns: FUNCTION hello_world RETURNS VARCHAR2
  • 26. Create Java Class Using Bfile-4 Your Java stored function (created from the binary file) is now available for use. To test it, type the following into SQLPlus SQL> select hello_world() from dual; OR SQL> variable myString varchar2(40); SQL> call hello_world() into :myString; SQL> print myString; Note that you can also call your stored function from any other PL/SQL procedure or function.
  • 27. Which Classes Are Loaded? -1 You can determine which Java "system" classes are currently loaded in Oracle by selecting from the dba_objects table. To determine which "user" classes are loaded, you can select from the user_objects table. For example, to determine the class name, created date, and status of your Java classes loaded in Oracle: select OBJECT_NAME, CREATED, STATUS from user_objects where object_type = 'JAVA CLASS' Note: classes with status "invalid" aren't necessarily invalid, they just haven't been compiled in Oracle yet.
  • 28. Which Classes Are Loaded? -2 If you use Toad, you can click on the Java tab of the schema browser to see which classes are loaded. In Toad, you can right-click on one of these classes and select "compile". If Oracle likes your class, you'll see the message, "Compiled without errors". If Oracle has rejected your class, you'll get an error message about why Oracle rejected it. (see next slide)
  • 29. Viewing Java Classes With Toad Viewing Java classes in a schema and compiling
  • 30. Loadjava Utility-1 Instead of using a tool like SQLPlus to load your Java class into Oracle, you might prefer using a command line tool like the loadjava utility This tool exists on the Oracle server in the $ORACLE_HOME/bin directory So if Oracle is installed on a UNIX server, the tool will reside on that server (not the Oracle client directory on a user's Windows machine). You can also run loadjava from an application like SQLPlus by calling sys.dbms_java.loadjava(...)
  • 31. Loadjava Utility-2 Loadjava loads Java source files, classes, JAR files, and other resources into the database where they are stored as Java schema objects Note: In Toad, you can find these Java schema objects on the Java tab of the Schema Browser window
  • 32. Loadjava Utility-3 With Oracle 9i (version 9.2), loadjava allows you to automatically publish Java classes as stored procedures by creating the corresponding call specs for methods contained in the processed classes With Oracle 8i, you have to create the call spec (procedure or function) yourself
  • 33. Loadjava Utility-4 According to Oracle, the Loadjava syntax is (assumes loadjava.bat is installed in the Oracle Home directory and the HelloWorld.class file is in the current directory of the same server) loadjava -user schema/password HelloWorld.class or loadjava -user schema/password HelloWorld.java I got an Oracle error with the syntax above. To load a java file to wdevprja on snowmass, I had to use loadjava -force -user wdevprja/wdevprja@snowmass:1521:wdev -thin MyClass.java
  • 34. Loadjava Utility-5 You can also execute this from SQLPlus like so: SQL> host loadjava -force -user wdevprja/mypassword@snowmass:1521:wdev -thin MyClass.java To load a jar file into wdevcnv (Oracle 9.2), you log into snowmass as user wdevcnv and loadjava -force -user wdevcnv/mypassword@snowmass:1526:wdevcnv -thin SQLExecutorFramework.jar
  • 35. Loadjava Utility-6 You can also use the sys.dbms_java.loadjava function in SQLPlus to load your Java class SQL>call sys.dbms_java.loadjava('-v -r -grant PUBLIC -synonym HelloWorld.java'); This example would load the class HelloWorld into the schema you logged into
  • 36. Class Resolver-1 The Oracle JVM uses a resolver to search for supporting classes when you call a method in the HelloWorld class. A supporting class is just a class that is referenced by your class. For example, if your class uses String objects, then the String class is a "supporting class" Oracle provides a default class resolver which searches the current schema and then PUBLIC PUBLIC classes include all the standard JDK classes If you want to access classes defined in another schema, you specify this other resolver on the loadjava command line
  • 37. Class Resolver-2 If you want to access classes defined in another schema, you specify this other resolver on the loadjava command line The following example uses a custom resolver spec which includes the SCHEMA1 schema, SCHEMA2 schema, and PUBLIC loadjava -resolve -resolver "((* SCHEMA1)(* SCHEMA2)(* PUBLIC))" This command would search SCHEMA1, SCHEMA2, and PUBLIC to resolve all class references in your code
  • 38. Class Resolver-3 You can also narrow the resolver spec to search for a subset of classes within a schema: loadjava -resolve -resolver '(("com/cexp/*" SCHEMA1)(* SCHEMA2)(* PUBLIC))' This command would search all classes whose package name begins with com.cexp in SCHEMA1, all classes in SCHEMA2, and all PUBLIC classes
  • 39. Compiling Classes In Oracle-1 You may be surprised to see that after you've loaded your classes into Oracle with the LoadJava utility, they are uncompiled (status "invalid"). Don't worry! Your classes will either be compiled automatically on first use or you can manually compile them yourself in a tool like SQLPlus: SQL> ALTER JAVA CLASS "com.cexp.wms.MyClass" RESOLVE; or SQL> ALTER JAVA SOURCE "com.cexp.wms.MyClass" COMPILE; You can also compile them in Toad (see next slide)
  • 40. Compiling Classes In Oracle-2 Here is Oracle's easy to understand diagram of Alter Java... ALTER JAVA SOURCE - used to compile a Java source ALTER JAVA CLASS - used to resolve (find classes referenced) a Java class ALTER JAVA CLASS "Agent" RESOLVER (("/home/java/bin/*" pm)(* public)) RESOLVE;
  • 41. Compiling Classes In Oracle-3 The invoker_rights_clause lets you specify whether the methods of the class execute with the privileges and in the schema of the user who defined it or with the privileges and in the schema of CURRENT_USER. It also determines how Oracle resolves external names in queries, DML operations, and dynamic SQL statements in the member functions and procedures of the type. Specify CURRENT_USER if you want the methods of the class to execute with the privileges of CURRENT_USER. This clause is the default and creates an "invoker-rights class." Specify DEFINER if you want the methods of the class to execute with the privileges of the user who defined it.
  • 42. Granting Permissions-1 Sometimes you will need to grant the Oracle JVM permissions in order for your Java stored procedure (or trigger) to function For example, if your Java class reads or writes from disk, you may need to grant the Oracle JVM certain file system permissions. For example: EXEC dbms_Java.Grant_Permission('wdevcnv', 'java.io.FilePermission', '<<ALL FILES>>', 'read, write, execute, delete'); where 'wdevcnv' is the schema name) For an example of exporting the contents of a BLOB datatype to the file system, see: http://www.oracle-base.com/Articles/8i/ExportBlob.asp
  • 43. Loading JAR files To load a JAR file into an Oracle 8.1.7 server named wdev.snowmass with user wdevprja on the standard port 1521, you could type the following in SQLPlus SQL> host loadjava -force -user wdevprja/mypassword@snowmass:1521:wdev -thin MyProject.jar (this command assumes that MyProject.jar is in the current directory)
  • 44. Compiling JARs With Toad Once you load your JAR file in Oracle 8.1.7, you'll need to compile the classes. Using a tool like Toad makes this easy
  • 45. Loadjava Summary The only drawback of loadjava is that it only works on the operating system on which Oracle resides. It also requires you to manually create a call spec. To recap, if you are developing your Java code on Windows and Oracle resides elsewhere (perhaps on UNIX), you need to do the following first copy the file somewhere on the UNIX box (perhaps via FTP) next call the loadjava utility next create a call spec (function or procedure) This is rather tedious. Ideally, we would find a tool that automates this whole process for us.
  • 46. Loadjava And Toad-1 You can use Toad to load Java classes into Oracle (it uses the loadjava utility). Go to the Tools Menu, Java Manager option. It must be able to find loadjava.bat in order to work.
  • 47. Drop Java Source/Class-1 You may want to drop a source file or class you've loaded into Oracle. Use the drop java source or drop java class command to do this. For example: SQL> drop java source "HelloWorld"; SQL> drop java source "com.cexp.wms.oracle.HelloWorld" SQL> drop java class "HelloWorld"; To drop your function (call spec) named HelloWorld: SQL> drop function hello_world; Toad makes it easy to drop classes and sources. Just go to the Java tab of the schema browser, right click on the object you want to drop, select "drop object". You can also drop the function on the Procs tab
  • 48. Drop Java Source/Class-2 You can also use the dropjava command line utility (installed on the same server as the database). For example: dropjava -u username/password myPackage.myClass dropjava -u username/password myJar.jar
  • 49. Exercise Using SQLPlus, create a test table in wdevprja called something like "MyName_Test". The table should have the following fields: EMPID (Number), FNAME (VARCHAR2) and LName (VARCHAR2). Put a couple records in it. Using Eclipse, create a Java stored procedure in package com.cexp.wms.oracle. Your class should be called "MyName_StoredProcTest" and your method should be called "insertRecord(String firstName, lastName)". This stored procedure can use standard JDBC or the SQLExecutor framework to insert records into your table. Load your Java stored procedure into the database and create a call spec for it. SQLPlus commands may be the easiest way to do this. Test your stored procedure by calling it from SQLPlus. Redirect System.out.println() output to the SQLPlus window to aid in debugging. Remember to drop your table when you are done. Also drop your Java stored procedure and your call spec.
  • 50. Problems Loading Java-1 Occasionally, one of your class files may compile fine with Sun JDK 1.3, but be rejected by Oracle. For example, one of the classes in my SQLExecutorFramework.jar file was rejected by Oracle because a function returned its value in a finally block (see next slide)
  • 51. Problems Loading Java-2 static int getDbType(Connection con) { try { .... } catch (SQLException e) { .... } finally { return(dbType); } }
  • 52. Problems Loading Java-3 When I compiled this class in Toad (go to Java tab of Schema browser and right click on Java classname), I got the following error from Oracle: JAVA CLASS WDEVPRJA.com/cexp/wms/jdbc/DatabaseType On line: 0 ORA-29545: badly formed class: at offset 78 of com.cexp.wms.jdbc.DatabaseType.getDbType return type is inconsistent with return opcode
  • 53. Problems Loading Java-4 When I compiled this class in Toad (go to Java tab of Schema browser and right click on Java classname), I got the following error from Oracle: JAVA CLASS WDEVPRJA.com/cexp/wms/jdbc/DatabaseType On line: 0 ORA-29545: badly formed class: at offset 78 of com.cexp.wms.jdbc.DatabaseType.getDbType return type is inconsistent with return opcode
  • 54. Problems Loading Java-5 When I rewrote my code like this, Oracle was happy: static int getDbType(Connection con) { try { .... } catch (SQLException e) { .... } return(dbType); }
  • 55. Problems Loading Java-6 The new code is probably better, so it was an easy decision to make the code change SQLExecutorFramework.jar now works in Oracle 8.1.7 The point here is that there may be times your Java classes are rejected by Oracle when you try to load them Use a tool like Toad to get the compile error from Oracle and then fix your classes accordingly
  • 56. Problems Using LoadJava-1 There is a bug in Oracle 8 that occurs when you use loadjava to re-load an already loaded CLASS file. Oracle seems to get confused and doesn't recompile the new class file correctly. Loading the .java (source) instead of the class file seems to work every time: host loadjava -force -user wdevprja/wdevprja@snowmass:1521:wdev -thin JeffStoredProcTest.java I don't know if this is a problem in Oracle 9.2 or not. To be safe, I'd recommend loading Java source files instead of class files (since Oracle has to recompile them anyway).
  • 57. Problems Using LoadJava-2 You can load a JAR file into Oracle with a single loadjava command: loadjava -force -user wdevprja/password@snowmass:1521:wdev -thin SQLExecutorFramework.jar Occasionally, a class in your JAR file might not get loaded into Oracle (version 8 at least). When you try to compile another class which uses this missing JAR file class, you'll get a compile error. My advice is to check that each class in your JAR is loaded into Oracle
  • 58. Problems Compiling/Running-1 If you ever get an error message like this: The following error has occurred: ORA-29549: class WDEVPRJA.com/cexp/wms/oracle/StoredProcTest has changed, Java session state cleared ORA-06512: at "WDEVPRJA.STOREDPROCTEST_CREATETABLE", line0 ORA-06512: at line 2 The Oracle docs say "Cause: A class in use by the current session was redefined or dropped, invalidating the current Java session state and requiring that it be cleared." It means that you've reloaded a Java class in Oracle and the new version is different (and needs to be recompiled) Just ignore this error and re-run the stored procedure. The error should go away on the 2nd attempt
  • 59. Problems Debugging-1 To view System.out.println in SQLPlus, you'll need to: set serveroutput on call dbms_java.set_output(5000); (Note: I had to execute this before EACH call to my stored procedure) If a runtime exception is thrown, you may not see any of your System.out.println statements (that preceded the runtime exception) at all!
  • 60. Problems Setting Query Timeout When I set a query timeout in a Java stored procedure like so: prepStatement.setQueryTimeout(15); prepStatement.executeUpdate(); //null pointer exception I got a NullPointerException when the executeUpdate() statement executed. Hence, I don't recommend setting a query timeout :-)
  • 61. Creating a Java Trigger-1 You can also write your Oracle triggers in Java. For example, you could write the following trigger class: import java.sql.*; public class EmployeeInsertTrigger { public static void onInsert(Connection con, Long[] newid) { Long NextSeqValue = new Long(0); //def to zero
  • 62. Creating a Java Trigger-2 try { //Get next id from the sequence String sql = "select emp_seq.nextval from dual"; PreparedStatement ps = con.prepareStatement(sql); ResultSet rs = ps.executeQuery(); while (rs.next ()) NextSeqValue = new Long(rs.getLong(1)); newid[0] = NextSeqValue; // Close the Statement stmt.close(); ps.close(); } catch(SQLException e) {} } }
  • 63. Creating a Java Trigger-3 Next, compile your Java class and then load it into the database: CREATE OR REPLACE JAVA CLASS USING BFILE (MyFolder, 'EmployeeInsertTrigger.class'); / Next you create your call spec: CREATE OR REPLACE PROCEDURE EMPLOYEE_INSERT( NEWID IN OUT NUMBER ) AS LANGUAGE JAVA NAME 'EmployeeInsertTrigger.onInsert( java.sql.Connection, java.lang.Long[])'; /
  • 64. Creating a Java Trigger-4 Finally, create your trigger which will fire before each insert into the Employee table: CREATE OR REPLACE TRIGGER EMPLOYEE_BEF_INS_TRG BEFORE INSERT ON EMPLOYEE FOR EACH ROW EMPLOYEE_INSERT( new.EMPLOYEE_ID ); / That's all there is to it!
  • 65. My Loadjava Utility-1 I've written a utility called JavaLoader which replaces the Oracle version. My LoadJava program (written in Java, of course) automates the whole process. Copies your class file to the UNIX server hosting Oracle Creates an Oracle directory alias Creates the Java class in Oracle using the "CREATE JAVA CLASS USING BFILE" command Creates the corresponding call spec Compiles the Java class in Oracle Deletes the temporary class file from the UNIX server
  • 66. My Loadjava Utility-2 JavaLoader uses a properties file to store the information required to perform all these tasks You can edit the "template" javaloader.properties file to load your own, custom Java classes
  • 67. My Loadjava Utility-3 # Properties for Jeff Smith's Load Java Program ftp.servername=uscobrmfa-ub-14.cexp.com ftp.username=jesmith oracle.connurl=jdbc:oracle:thin:@SNOWMASS:1521:WDEVCNV oracle.username=wdevcnv oracle.password=wdevcnv java.classname=StoredProcTest.class java.package=com.cexp.wms.oracle java.methodname=createTable
  • 68. My Loadjava Utility-4 #STORED PROCEDURE EXAMPLE (ORACLE CALL SPEC) cs0=CREATE OR REPLACE PROCEDURE cs1=StoredProcTest_createTable(table_name IN VARCHAR2) AS language java cs2=NAME 'com.cexp.wms.oracle.StoredProcTest.createTable(java.lang.String)' cs3= cs4= cs5= #STORED FUNCTION EXAMPLE (ORACLE CALL SPEC) #cs0=CREATE OR REPLACE FUNCTION StoredProcTest_getFullName(fname IN #cs1=VARCHAR2, lname IN VARCHAR2) #cs2=return VARCHAR2 AS language java #cs3= NAME 'com.cexp.wms.oracle.StoredProcTest.getFullName(java.lang.String, #cs4=java.lang.String) return java.lang.String' #cs5=
  • 69. My Loadjava Utility-5 Syntax: Javaloader [password] [optional: properties filename]. If you leave the properties filename blank, the name "javaloader.properties" is assumed (similar to the way Ant assumes a file called build.xml will exist) Example: javaloader mypassword Example: javaloader mypassword javaloader.properties
  • 70. My Loadjava Utility-6 For more information and to download the utility, see: http://expressway2.cexp.com/info_services/D&L_Systems/java/ JavaLoader.htm
  • 71. A Look Into The Crystal Ball Given the rising popularity of Java, Oracle will likely migrate the database in that direction. While PL/SQL support won't be going away, new development at Oracle will probably focus on Java stored procedures, functions and triggers Other databases are also moving in the direction of Java Postgres supports Java stored procedures (PL/PGJ) MySQL may follow suit But you probably won't see Microsoft add Java stored procedures to SQL Server before hell freezes over!
  • 72. Resources Oracle's Java Stored Procedure Samples: http://technet.oracle.com/sample_code/tech/java/jsp/oracle9ijsp.html