Calling Java code from PLSQL

Create a simple java class.
[oracle@db ~]$ sqlplus oratt/oracle

SQL*Plus: Release 11.2.0.3.0 Production on Thu Feb 7 18:16:27 2013

Copyright (c) 1982, 2011, Oracle.  All rights reserved.

Connected to:
Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - Production
With the Partitioning and Real Application Testing options

SQL> ! cat Factorial.java
public class Factorial {
  public static int getFactorialValue(int a) {
    if (a == 1) return 1;
    else return a * getFactorialValue(a - 1);
  }
}

SQL>
There are a lot of options for loading the java class (I'll describe only two of them).

1. Load the file by using loadjava utility
SQL> ! loadjava -user oratt/oracle Factorial.java

SQL>

select object_name, object_type from user_objects where object_type like 'J%';

SQL> select object_name, object_type from user_objects where object_type like 'J%';

OBJECT_NAME                    OBJECT_TYPE
------------------------------ -------------------
Factorial                      JAVA SOURCE
Factorial                      JAVA CLASS

SQL>
2. Create java statement Before that let's delete Factorial class from database
SQL> !dropjava -user oratt/oracle Factorial.java

SQL> select object_name, object_type from user_objects where object_type like 'J%';

no rows selected

SQL> CREATE JAVA SOURCE NAMED "Factorial" AS
   2   public class Factorial {
   3     public static int getFactorialValue(int a) {
   4       if (a == 1) return 1;
   5       else return a * getFactorialValue(a - 1);
   6     }
   7   }
   8 /  

Java created.

SQL> select object_name, object_type from user_objects where object_type like 'J%';

OBJECT_NAME                    OBJECT_TYPE
------------------------------ -------------------
Factorial                      JAVA SOURCE
Factorial                      JAVA CLASS

SQL>
Now, create a package.
SQL> CREATE OR REPLACE PACKAGE java_pack AS
   2   function factorial_func(x in pls_integer) return pls_integer;
   3 END java_pack;
   4 /

Package created.

SQL> CREATE OR REPLACE PACKAGE BODY java_pack AS
   2
   3   function factorial_func(x in pls_integer)
   4    return  pls_integer
   5   as language java
   6   name 'Factorial.getFactorialValue (int) return int';
   7
   8 END java_pack;
   9 /

Package body created.

SQL>

SQL> exec dbms_output.put_line(java_pack.factorial_func(15));
2004310016

PL/SQL procedure successfully completed.

SQL> select java_pack.factorial_func(10) from dual;

JAVA_PACK.FACTORIAL_FUNC(10)
----------------------------
                     3628800

SQL>
Is you can see, its very easy to use Java code in PLSQL. There is only one thing you should remember - it is a Oracle Database JVM version (DB Version 11.2 - Java 1.5.0 (1.5.0_01)) I would recommend you to read the following notes:
  • What Version of Java is Compatible With The Database JVM? [ID 438294.1] 
  • How to identify JDK version running in Oracle Database JVM [ID 331673.1]

Комментариев нет: