Java external sp: with Java Class. Part 1

External Procedures using Java class file:

If your java code is just using core Jave (no external lib) then using the class file is super easy.

But things get a little tricky when your code is using some external lib. I prefer to use jar in that case.

Example 1:  Add 2 numbers.

SQL Procedure will look like this:

1. Create or replace procedure AddNumbers(
2. In Number1 numeric(4),
3. In Number2 numeric(4),
4. Out total numeric(5)
5. )
6. PARAMETER STYLE JAVA
7. LANGUAGE JAVA 
8. EXTERNAL NAME " ** QUALIFIED JAVA METHOD NAME ** ";
  1. A simple SP with 2 in parameters and 1 out paramter
  2. ** QUALIFIED JAVA METHOD NAME **: more  later on this page

Java Code: Calculator.java

1. public class Calculator{
2.  public static void add(int number1, int number2, int[] total)
3.   {
4.      total[0] = number1+number2;
5.    }
6. }
  1. Line 2: we defined the java method we are going to use with following attributes
    1. public: the method must be public
    2. static : this is also a must
    3. void : this is also a must
  2. Line 2: This method has 3 parameters
    1. int number1 : it will receive the value of the “In Number1 numeric(4)”
    2. int number2 : it will receive the value of the “In Number2 numeric(4)”
    3. int[] total: It will populate the value in “Out total numeric(5)”. This is a Java array.
      1. When SQL calls this method, it pass this parameter as ONE length array.
      2. So this array can only contain one value.
      3. In java array starts with index 0.
      4. In our code we populate the index 0 (line 4) of this array with the result. And SQL uses this value as the OUT parameter.

 

“EXTERNAL NAME”

8. EXTERNAL NAME " ** QUALIFIED JAVA METHOD NAME ** ";
  1. When using RPG, we point “EXTERNAL NAME” to the RPG program or module.
    1. With/without service program name
    2. With/without library name.
  2. and SQL knows where to find the code to execute.
  3. Same is valid in case of Java. but
    1. Java’s code is not available on QSYS file system.
    2. But there is a predefined IFS location where SQL looks for java classes.
      1.  that IFS location is “/QIBM/UserData/OS400/SQLLib/Function”
  4. So, SQL knows where to look for Java class files. But still we need to tell SQL which CLASS and METHOD we need to call.
    1. for the example above
      1. Class name = “Calculator
      2. Method name = “add
    2. no need to define the parameters.(same as External RPG SP)
8. EXTERNAL NAME "Calculator.add"

 

Leave a Reply

Your email address will not be published. Required fields are marked *