---
title: "Java stored functions and procedures"
description: "Write CoraDB stored functions and procedures in Java: load classes, publish them with CREATE FUNCTION/PROCEDURE, map types, call them."
url: "https://www.coradb.ai/manual/sql/jsp.html"
markdown_url: "https://www.coradb.ai/manual/markdown/sql/jsp.md"
product: "CoraDB"
version: "1.0"
keywords: "coradb java stored procedure, java stored function, create function, create procedure, loadjava, javasp, return cursor, out parameter, server-side jdbc, jdbc:default:connection"
---

# Java stored functions and procedures

CoraDB stored functions and procedures are written in Java. They run in a Java virtual machine (JVM) hosted by the CoraDB *Java SP server*, can use SQL through a server-side JDBC connection, and are called from SQL statements, from the **CALL** statement or from applications through JDBC.

- A **stored function** returns a value and can be used in expressions, for example in a **SELECT** list.
- A **stored procedure** returns no value; it can return results through **OUT** parameters.

Java is the only language for stored functions and procedures.

## Enabling the Java SP server

1. Set the server parameter [java_stored_procedure](https://www.coradb.ai/manual/admin/config_other.html) to `yes` in `coradb.conf` (the default is `no`) and restart the database server.
2. Start the Java SP server for the database and check its status:

```bash
coradb javasp start e-commerce
coradb javasp status e-commerce
```

`status` shows the process ID, port and JVM options of the server. See [CoraDB Java stored procedure server](https://www.coradb.ai/manual/admin/control_javasp.html) for the `javasp` commands and [Configuring for CoraDB Java SP server](https://www.coradb.ai/manual/admin/control_javasp.html#configuring-for-coradb-java-sp-server) for its settings. Calling a Java stored function while the server is not running fails with `Java VM is not running.`

## Writing a Java stored function

The whole workflow, for a function that returns the total of an order of the e-commerce database:

**1. Write and compile the Java class.** The methods called from SQL must be `public static`.

```java

public class OrderSp {
    public static BigDecimal orderTotal(int orderId) throws SQLException {
        Connection conn = DriverManager.getConnection("jdbc:default:connection:");
        PreparedStatement ps = conn.prepareStatement(
            "SELECT SUM(p.unit_price * oi.quantity * (100 - oi.discount_pct) / 100) "
            + "FROM order_items oi JOIN product p ON p.id = oi.product_id WHERE oi.order_id = ?");
        ps.setInt(1, orderId);
        ResultSet rs = ps.executeQuery();
        BigDecimal total = rs.next() ? rs.getBigDecimal(1) : null;
        rs.close();
        ps.close();
        return total;
    }
}
```

```bash
javac OrderSp.java
```

**2. Load the class into the database** with [loadjava](https://www.coradb.ai/manual/sql/jsp.html#loadjava-utility):

```bash
loadjava e-commerce OrderSp.class
```

**3. Publish it** with a call specification:

```sql
CREATE FUNCTION order_total(p_order_id INT) RETURN NUMERIC(12,2)
AS LANGUAGE JAVA
NAME 'OrderSp.orderTotal(int) return java.math.BigDecimal';
```

**4. Call it**:

```sql
SELECT id, order_total(id) FROM orders WHERE customer_id = 102;
```

## Server-side JDBC

Inside a stored function or procedure, connect to the calling database with the URL `jdbc:default:connection:`:

```java
Connection conn = DriverManager.getConnection("jdbc:default:connection:");
```

This connection belongs to the transaction of the caller. Its statements are committed or rolled back with that transaction, and `conn.commit()` and `conn.rollback()` inside the Java method have no effect.

A stored procedure can also open an ordinary JDBC connection to another database (URL `jdbc:coradb:host:port:database:user:password:`; see [JDBC driver](https://www.coradb.ai/manual/api/jdbc.html)). Such a connection is a separate transaction: commit and close it explicitly in the Java code.

`System.getProperty("coradb.server.version")` returns the CoraDB version when the code runs inside the Java SP server, and **NULL** elsewhere; use it to check where a class is running.

## loadjava utility

**loadjava** copies a compiled Java class or a JAR file into the database's Java directory, from where the Java SP server loads it.

```bash
loadjava [-y | --overwrite] database_name java_class_or_jar_file
```

- `-y`, `--overwrite`: overwrite a file of the same name without asking. Without it, **loadjava** asks before overwriting.

## Publishing: CREATE FUNCTION and CREATE PROCEDURE

A loaded class is called from SQL only after it is published with a *call specification*, which names the Java method and maps its parameters and return value to SQL types.

```sql
CREATE [OR REPLACE] FUNCTION function_name [ ( parameter [, parameter ...] ) ]
RETURN sql_type
{ IS | AS } LANGUAGE JAVA
NAME 'class_name.method_name ( [java_type [, java_type ...]] ) return java_type'
[ COMMENT 'comment' ];

CREATE [OR REPLACE] PROCEDURE procedure_name [ ( parameter [, parameter ...] ) ]
{ IS | AS } LANGUAGE JAVA
NAME 'class_name.method_name ( [java_type [, java_type ...]] )'
[ COMMENT 'comment' ];

parameter ::= parameter_name [ IN | OUT | IN OUT | INOUT ] sql_type [ COMMENT 'comment' ]
```

- **OR REPLACE** replaces an existing function or procedure of the same name.
- Names of stored functions and procedures are not case-sensitive. A name can have up to 254 bytes, and a function or procedure up to 64 parameters.
- Parameters are **IN** by default. An **OUT** or **INOUT** (**IN OUT**) parameter is passed to Java as an array of length 1; the Java method returns its value in the first element.
- Java types are written with their full names (`java.lang.String`, `java.math.BigDecimal`), primitive types as is (`int`, `short`).
- CoraDB does not check the call specification against the Java class when it is published; a mismatch shows up when the function is called. The SQL return type of the call specification determines the type of the result.

```sql
CREATE OR REPLACE FUNCTION order_total(p_order_id INT COMMENT 'order id') RETURN NUMERIC(12,2)
IS LANGUAGE JAVA
NAME 'OrderSp.orderTotal(int) return java.math.BigDecimal'
COMMENT 'sum of order lines';

CREATE PROCEDURE add_order_item(p_order_id INT, p_product_id INT, p_quantity SHORT)
AS LANGUAGE JAVA
NAME 'OrderSp.addOrderItem(int, int, short)';

CREATE PROCEDURE stock_of(p_product_id IN INT, p_units OUT INT)
AS LANGUAGE JAVA
NAME 'OrderSp.stockOf(int, java.lang.Integer[])';
```

### Data type mapping

| SQL type | Java types |
|---|---|
| CHAR, VARCHAR | `java.lang.String`, `java.sql.Date`, `java.sql.Time`, `java.sql.Timestamp`, `java.lang.Byte`, `java.lang.Short`, `java.lang.Integer`, `java.lang.Long`, `java.lang.Float`, `java.lang.Double`, `java.math.BigDecimal`, `byte`, `short`, `int`, `long`, `float`, `double` |
| NUMERIC, SHORT, INT, BIGINT, FLOAT, DOUBLE | `java.lang.Byte`, `java.lang.Short`, `java.lang.Integer`, `java.lang.Long`, `java.lang.Float`, `java.lang.Double`, `java.math.BigDecimal`, `java.lang.String`, `byte`, `short`, `int`, `long`, `float`, `double` |
| DATE, TIME, TIMESTAMP, DATETIME | `java.sql.Date`, `java.sql.Time`, `java.sql.Timestamp`, `java.lang.String` |
| SET, MULTISET, LIST (SEQUENCE) | `java.lang.Object[]`, arrays of primitive types, `java.lang.Integer[]`, … |
| OBJECT | `coradb.sql.CORADBOID` |
| CURSOR (return type only) | `java.sql.ResultSet` |

### Listing stored functions and procedures

[db_stored_procedure](https://www.coradb.ai/manual/sql/catalog_views.html#db_stored_procedure) and [db_stored_procedure_args](https://www.coradb.ai/manual/sql/catalog_views.html#db_stored_procedure_args) list the published functions and procedures and their parameters, with their comments:

```sql
SELECT sp_name, sp_type, return_type, arg_count, target, comment
FROM db_stored_procedure ORDER BY sp_name;
```

| sp_name | sp_type | return_type | arg_count | target | comment |
|---|---|---|---|---|---|
| add_order_item | PROCEDURE | void | 3 | OrderSp.addOrderItem(int, int, short) | NULL |
| order_total | FUNCTION | NUMERIC | 1 | OrderSp.orderTotal(int) return java.math.BigDecimal | Sum of order lines |
| stock_of | PROCEDURE | void | 2 | OrderSp.stockOf(int, java.lang.Integer[]) | NULL |

```sql
SELECT sp_name, index_of, arg_name, data_type, mode, comment
FROM db_stored_procedure_args ORDER BY sp_name, index_of;
```

| sp_name | index_of | arg_name | data_type | mode | comment |
|---|---|---|---|---|---|
| add_order_item | 0 | p_order_id | INTEGER | IN | NULL |
| add_order_item | 1 | p_product_id | INTEGER | IN | NULL |
| add_order_item | 2 | p_quantity | SHORT | IN | NULL |
| order_total | 0 | p_order_id | INTEGER | IN | order id |
| stock_of | 0 | p_product_id | INTEGER | IN | NULL |
| stock_of | 1 | p_units | INTEGER | OUT | NULL |

### DROP FUNCTION and DROP PROCEDURE

```sql
DROP FUNCTION function_name [, function_name ...];
DROP PROCEDURE procedure_name [, procedure_name ...];
```

```sql
DROP FUNCTION order_total;
DROP PROCEDURE add_order_item, stock_of;
```

A stored function or procedure can be dropped by its owner and by **DBA** and the members of the **DBA** group. Its owner can be changed with [ALTER FUNCTION … OWNER TO](https://www.coradb.ai/manual/sql/authorization.html#alter--owner).

## Calling stored functions and procedures

### From SQL

A stored function can be used wherever an expression is allowed:

```sql
SELECT order_total(1);
SELECT id, order_date, order_total(id) AS total FROM orders WHERE customer_id = 102;
```

### With CALL

```sql
CALL procedure_name ( [argument [, argument ...]] );
CALL function_name ( [argument [, argument ...]] ) INTO :variable;
```

```sql
CALL add_order_item(1, 1618, 2);     -- adds 2 x Gobi HeatTec Tee to order 1
CALL order_total(1) INTO :total;
```

Arguments are literals or session variables (`:name`). A variable passed to an **OUT** or **INOUT** parameter receives its value:

```sql
CALL stock_of(1618, :units);
SELECT :units;
```

**CALL** is also used for [methods](https://www.coradb.ai/manual/sql/method.html). Without **ON** *target*, CoraDB first looks for a stored function or procedure of that name and then for a method. Calling a name that is neither fails with:

```text
ERROR: Stored procedure/function 'deposit' does not exist.
```

when the call has no arguments, and, when it has arguments (which could be a method call on the first argument), with:

```text
ERROR: Methods require an object as their target.
```

An argument of **CALL** cannot be another **CALL** or a subquery.

If the Java code throws an exception, it is written to the `<database>_java.log` file. To print exceptions on the console instead, set the handler in `$CORADB/java/logging.properties` to `java.util.logging.ConsoleHandler`.

### From a Java application

Applications call stored functions and procedures through a JDBC `CallableStatement`:

```java

public class AddItem {
    public static void main(String[] args) throws Exception {
        Connection conn = DriverManager.getConnection("jdbc:coradb:localhost:33000:e-commerce:::", "dba", "");
        conn.setAutoCommit(false);

        CallableStatement cs = conn.prepareCall("CALL add_order_item(?, ?, ?)");
        cs.setInt(1, 1);
        cs.setInt(2, 1618);
        cs.setShort(3, (short) 2);
        cs.executeUpdate();
        cs.close();

        CallableStatement fn = conn.prepareCall("? = CALL order_total(?)");
        fn.registerOutParameter(1, Types.NUMERIC);
        fn.setInt(2, 1);
        fn.execute();
        System.out.println("total: " + fn.getBigDecimal(1));
        fn.close();

        conn.commit();
        conn.close();
    }
}
```

The procedure behind `add_order_item` uses the server-side connection, so its insert is part of the application's transaction and is committed by `conn.commit()`:

```java
public static void addOrderItem(int orderId, int productId, short quantity) throws SQLException {
    Connection conn = DriverManager.getConnection("jdbc:default:connection:");
    PreparedStatement ps = conn.prepareStatement(
        "INSERT INTO order_items (order_id, product_id, quantity, discount_pct) VALUES (?, ?, ?, 0)");
    ps.setInt(1, orderId);
    ps.setInt(2, productId);
    ps.setShort(3, quantity);
    ps.executeUpdate();
    ps.close();
}
```

## Cautions

### Precision of return values and OUT parameters

CoraDB converts the value returned by Java (or put into an **OUT** parameter) to the SQL type of the call specification, but does not apply its length or precision. A function declared `RETURN CHAR(5)` that returns an 11-character Java string returns all 11 characters; limit the length in the Java code if needed.

### Returning a ResultSet

A function that returns a `java.sql.ResultSet` is declared with the return type **CURSOR**. Before returning the result set, cast it to `CORADBResultSet` and call `setReturnable()`:

```sql
CREATE FUNCTION low_stock(p_limit INT) RETURN CURSOR
AS LANGUAGE JAVA
NAME 'OrderSp.lowStock(int) return java.sql.ResultSet';
```

```java

public static ResultSet lowStock(int limit) throws SQLException {
    Connection conn = DriverManager.getConnection("jdbc:default:connection:");
    PreparedStatement ps = conn.prepareStatement(
        "SELECT id, name, units_in_stock FROM product WHERE units_in_stock < ? ORDER BY units_in_stock");
    ps.setInt(1, limit);
    ResultSet rs = ps.executeQuery();
    ((CORADBResultSet) rs).setReturnable();
    return rs;
}
```

The caller registers the result as `Types.JAVA_OBJECT` and casts it back to `ResultSet`. Such a function can be called only through a JDBC `CallableStatement`, and a result set cannot be passed as an **IN** argument.

```java
CallableStatement cs = conn.prepareCall("? = CALL low_stock(?)");
cs.registerOutParameter(1, Types.JAVA_OBJECT);
cs.setInt(2, 5);
cs.execute();
ResultSet rs = (ResultSet) cs.getObject(1);
while (rs.next()) {
    System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getShort(3));
}
rs.close();
```

### Collection parameters

A collection (**SET**, **MULTISET**, **LIST**) parameter is passed as a Java array. For an **OUT** or **INOUT** collection, the array is wrapped in another array of length 1 (a two-dimensional array), and the method replaces its first element with the new collection:

```sql
CREATE PROCEDURE add_tag(tags IN OUT SET, tag STRING)
AS LANGUAGE JAVA
NAME 'TagSp.addTag(java.lang.Object[][], java.lang.String)';
```

```java
public static void addTag(Object[][] tags, String tag) {
    java.util.List<Object> list = new java.util.ArrayList<>();
    if (tags[0] != null) {
        list.addAll(java.util.Arrays.asList(tags[0]));
    }
    list.add(tag);
    tags[0] = list.toArray();
}
```

### Object parameters

Object references are passed as `coradb.sql.CORADBOID` values; use the OIDs that the server passes in or that queries return, and declare **OUT** and **INOUT** object parameters as `CORADBOID[]`. Only tables created with **DONT_REUSE_OID** have referable objects.
