13 java in oracle

72
Java Training Java in Oracle Written by Jeff Smith

Upload: graham-royce

Post on 26-Jan-2015

128 views

Category:

Technology


0 download

DESCRIPTION

 

TRANSCRIPT

Page 1: 13 java in oracle

Java TrainingJava in Oracle

Written by Jeff Smith

Page 2: 13 java in oracle

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? :-)

Page 3: 13 java in oracle

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!

Page 4: 13 java in oracle

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

Page 5: 13 java in oracle

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

Page 6: 13 java in oracle

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?

Page 7: 13 java in oracle

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?

Page 8: 13 java in oracle

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

Page 9: 13 java in oracle

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

Page 10: 13 java in oracle

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.

Page 11: 13 java in oracle

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)

Page 12: 13 java in oracle

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

Page 13: 13 java in oracle

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

Page 14: 13 java in oracle

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!

Page 15: 13 java in oracle

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

Page 16: 13 java in oracle

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

Page 17: 13 java in oracle

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

Page 18: 13 java in oracle

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)

Page 19: 13 java in oracle

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

Page 20: 13 java in oracle

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';

Page 21: 13 java in oracle

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)';

Page 22: 13 java in oracle

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?

Page 23: 13 java in oracle

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

Page 24: 13 java in oracle

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;

Page 25: 13 java in oracle

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

Page 26: 13 java in oracle

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.

Page 27: 13 java in oracle

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.

Page 28: 13 java in oracle

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)

Page 29: 13 java in oracle

Viewing Java Classes With Toad

Viewing Java classes in a schema and compiling

Page 30: 13 java in oracle

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(...)

Page 31: 13 java in oracle

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

Page 32: 13 java in oracle

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

Page 33: 13 java in oracle

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

Page 34: 13 java in oracle

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

Page 35: 13 java in oracle

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

Page 36: 13 java in oracle

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

Page 37: 13 java in oracle

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

Page 38: 13 java in oracle

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

Page 39: 13 java in oracle

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)

Page 40: 13 java in oracle

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;

Page 41: 13 java in oracle

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.

Page 42: 13 java in oracle

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

Page 43: 13 java in oracle

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)

Page 44: 13 java in oracle

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

Page 45: 13 java in oracle

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.

Page 46: 13 java in oracle

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.

Page 47: 13 java in oracle

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

Page 48: 13 java in oracle

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

Page 49: 13 java in oracle

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.

Page 50: 13 java in oracle

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)

Page 51: 13 java in oracle

Problems Loading Java-2static int getDbType(Connection con)

{

try

{

....

}

catch (SQLException e)

{

....

}

finally

{

return(dbType);

}

}

Page 52: 13 java in oracle

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

Page 53: 13 java in oracle

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

Page 54: 13 java in oracle

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

}

Page 55: 13 java in oracle

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

Page 56: 13 java in oracle

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

Page 57: 13 java in oracle

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

Page 58: 13 java in 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

Page 59: 13 java in oracle

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!

Page 60: 13 java in oracle

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 :-)

Page 61: 13 java in oracle

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

Page 62: 13 java in oracle

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) {}

}

}

Page 63: 13 java in oracle

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[])';

/

Page 64: 13 java in oracle

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!

Page 65: 13 java in oracle

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

Page 66: 13 java in oracle

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

Page 67: 13 java in oracle

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

Page 68: 13 java in oracle

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=

Page 69: 13 java in oracle

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

Page 70: 13 java in oracle

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

Page 71: 13 java in oracle

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!

Page 72: 13 java in oracle

Resources

Oracle's Java Stored Procedure Samples:

http://technet.oracle.com/sample_code/tech/java/jsp/oracle9ijsp.html