WildFly JPA subsystem implements the JPA 2.1 container-managed requirements. JPA 2.1 introduces the support for the stored procedures. Now you can manage a stored procedure from your database directly in your Java code. In this sample, we will see how to execute a stored procedure in JPA.
Suppose we have this simple function; it returns a sum of two numbers in our H2 database:
CREATE ALIAS my_sum AS $$
int my_sum(int x, int y) {
return x+y;
} $$;
As the first thing, we need to create a stored procedure query through our Entity Manager specifying the name of the function:
StoredProcedureQuery query = entityManager.createStoredProcedureQuery("my_sum");
Now we can register and pass two values as input:
query.registerStoredProcedureParameter("x", Integer.class, IN);
query.registerStoredProcedureParameter("y", Integer.class, IN);
query.setParameter("x",5);
query.setParameter("y",5);
Execute the query:
query.execute();
And take the result:
Integer sum = (Integer) query.getSingleResult();
The result will be 9.