Thursday, August 26, 2010

Creating and Deploying Your First Application on the OracleJVM

Let's see how to create and load a simple Java class in the database and execute a method from the command line. Listing 1, shown below is the source code for firstclass.java.sql

Listing 1. Source code for firstclass.java.sql
create or replace java source named FirstClass as
public class FirstClass{
public static String greeting(String name){
return "Hello " + name + "!";
}
}
/
create
or replace function firstclass_greeting (name varchar2) return varchar as
language java name
'FirstClass.greeting(java.lang.String)
return java.lang.String';
/

As you can see, the first create statement encloses the pure-Java source code for a class named FirstClass (the first create statement is terminated by the "/"). When this statement is executed, then your Java class will be loaded in the OracleJVM. The second create statement associates the FirstClass.greeting() method with a callable function name of firstclass_greeting(). The second create statement is not necessary to load, compile, or initialize your Java class, but it provides a PL/SQL wrapper around your Java class so that entities in the SQL engine can call it. One more thing to notice about Listing 1: our PL/SQL wrapper is creating a functionbecause of the fact that we're returning something (in this case, a String) after execution. Later on, you should notice that I'll create a procedure when I want to wrap a Java void method.

Now when you load firstclass.java.sql into SQLPlus and execute it, then you should see the following results, as shown in Listing 2

Listing 2. The Results of Executing firstclass.java.sql
SQL> @firstclass.java.sql

Java created.

Function created.

So now we have our class loaded in the OracleJVM, and we also have a function that maps to our class's static method. So let's call that function and see what happens:

Listing 3. The Results of Calling the firstclass_greeting() function
SQL> select firstclass_greeting('Bruce') from dual;

FIRSTCLASS_GREETING
('BRUCE')
--------------------------------------------------------------------------------
Hello Bruce!
 

No comments:

Post a Comment