using Spring jdbctemplate to invoke a oracle function returning cursor - oracle

Hi I am using spring jdbctemplate to invoke an oracle function which takes an integer input.
Oracle function is :
FUNCTION get_key_types (type_id IN integer)
RETURN tcur_key_types_det
IS
lv_cur tcur_key_types_det;
BEGIN
IF type_id IS NULL
THEN
RAISE KEY_ERROR;
ELSE
OPEN lv_cur FOR
SELECT key_criteria_cd,
key_type_name,
KEY_COLUMN_TXT,
data_type_cd
FROM key_criteria
WHERE criteria_type_id = type_id
ORDER BY key_type_name;
END IF;
RETURN lv_cur;
END get_key_types;
I have a Java class that extends from Class StoredProcedure which passes and integer argument to invoke the oracle function as follows.
public class KeyTypeService extends StoredProcedure{
public KeyTypeService(DataSource dataSource,String sqlString) {
setDataSource(dataSource);
setFunction(true);
setSql(sqlString);
declareParameter(new SqlParameter("type_id",Types.INTEGER));
declareParameter(new SqlOutParameter("functionName",OracleTypes.CURSOR,new KeyTypeMapper()));
compile();
}
public Map execute(int category_id) {
Map<String, Object> inputs = new HashMap<String, Object>();
inputs.put("type_id", category_id);
Map output = execute(inputs);
return output;
}
}
I invoke the oracle function as follows.
int i = 60;
KeyTypeService keyTypeService = new KeyTypeService((DataSource)c.getBean ("DataSource"),"get_key_types");
map = keyTypeService.execute(i);
I get the following error indicating that I am not passing the correct data type expected.
PLS-00306: wrong number or types of arguments in call to 'get_key_types'
ORA-06550: line 1, column 7:
PL/SQL: Statement ignored
Any help would be highly appreciated..

Since my comment was correct:
The out parameter must come first.
Spring documentation might not explicitly talk about the order but the parameter order must be the same order as when you would call a pl/sql function without spring. I.e.:
out = call pacakge.function(in)

Related

How to create a dummy function in H2 embbeded db for integration test

I have a spring boot application that connects to an oracle database. The project contains a service class (userService) that calls the function VALIDATEUSER(USERNAME IN VARCHAR2,PASSWD IN VARCHAR2) in oracle and return 1 if user is valid and 0 invalid.
I need to create the same function in h2 db that always return true for my integration test.
Basically I wanted to created the function in sql script and load it during integration test as follows:
#Test
#Sql(scripts={"classpath:/sql/createFunction.sql"})
public void testUserInfo() throws Exception {
// userService calls VALIDATEUSER function
userService.isUserValid("testdb", "testdb");
}
How to create the function VALIDATEUSER in h2?
Thanks in advance.
You can execute the following SQL in H2 to create a function that accepts two VARCHAR parameters and returns an INTEGER result 1.
CREATE ALIAS VALIDATEUSER AS $$int validateUser(String name, String password) { return 1; }$$
Try this
CREATE ALIAS functionName AS 'int methodName(String name, String password) { return 1; }'
in Java you can use like this
Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection(
"jdbc:h2:mem:", "sa", "");
Statement stat = conn.createStatement();
// Using a custom Java function
stat.execute("CREATE ALIAS functionName AS 'int methodName(String name, String password) { return 1; }' ");
stat.close();
conn.close();

EclipseLink: call oracle StoredFunc with IN table type

I'm trying to call an oracle stored function using eclipselink 2.6.5, the storedfunction has an oracle type input.
This is te stored func:
create or replace function TEST_FUNC(PAR1 IN VARCHAR2, PAR2 IN MY_TYPE_T)
return varchar2 is
begin
if PAR2 is null then
return (PAR1 || ' 0');
else
return(PAR1 || ' ' || PAR2.count);
end if;
end TEST_FUNC;
This is type declaration:
CREATE OR REPLACE MY_TYPE_T as table of MY_TYPE_R
CREATE OR REPLACE TYPE MY_TYPE_R as object
(
COD_P VARCHAR2(3),
COD_S VARCHAR2(10)
)
This is the type mapping:
#Embeddable
#Struct(name="MY_TYPE_R", fields= {"COD_P", "COD_S"})
#PLSQLTable(
name="MY_TYPE_R",
compatibleType="MY_TYPE_T",
nestedType="MY_TYPE_R"
)
public class MyRecordType {
#Column(name="COD_P")
private String codP;
#Column(name="COD_S")
private String codS;
//costructors, getter and setter...
}
This is the stored mapping:
#NamedPLSQLStoredFunctionQuery(
name="testFunc",
functionName="TEST_FUNC",
returnParameter=#PLSQLParameter(
name="RESULT",
databaseType = "VARCHAR_TYPE"),
parameters = {
#PLSQLParameter(name = "firstParam", queryParameter="PAR1", databaseType = "VARCHAR_TYPE"),
#PLSQLParameter(name = "secondParam", queryParameter="PAR2", databaseType = "MY_TYPE_T"),
}
)
This is the call:
#Test
public void testFuncTest() {
List<MyRecordType> recTypeList = new ArrayList<MyRecordType>();
MyRecordType rec = new MyRecordType();
rec.setCodP("PValue");
rec.setCodS("SValue");
recTypeList.add(rec);
Query query = getEM().createNamedQuery("testFunc");
query.setParameter("firstParam", "FOO");
query.setParameter("secondParam", recTypeList);
Assert.assertEquals("FOO 1", query.getSingleResult());
}
When I execute the test I get:
PLS-00306: wrong number or types of arguments in call to 'TEST_FUNC'
Actually reading the documentation on #PLSQTable I'm a bit confused on the tree parameters:
name
compatibleType
nestedType
Anyone has some suggestion?
First you'll want to use the OracleObject annotation to define your fields into an Oracle object. It's somewhat duplicate to Struct but required anyways.
#OracleObject(
name = "MY_TYPE_R"
, javaType = MyRecordType.class
, fields = {
#PLSQLParameter(name = "COD_P")
,#PLSQLParameter(name = "COD_S")
}
)
For the PLSQLTable you want
#NamedPLSQLStoredFunctionQuery(
name="testFunc",
functionName="TEST_FUNC",
returnParameter=#PLSQLParameter(
name="RESULT",
databaseType = "VARCHAR_TYPE"),
parameters = {
#PLSQLParameter(name = "PAR1", queryParameter="PAR1", databaseType = "VARCHAR_TYPE"),
#PLSQLParameter(name = "PAR2", queryParameter="PAR2", databaseType = "MY_TYPE_T"),
}
)
so the name needs to match what's in your function. The PLSQL table piece looks right, I believe the OracleObject part was your missing component and causing your error.

How to properly call PostgreSQL functions (stored procedures) within Spring/Hibernate/JPA?

I'm using Spring MVC 4, Hibernate and PostgreSQL 9.3 and have defined function (stored procedure) inside Postgres like this:
CREATE OR REPLACE FUNCTION spa.create_tenant(t_name character varying)
RETURNS void AS
$BODY$
BEGIN
EXECUTE format('CREATE SCHEMA IF NOT EXISTS %I AUTHORIZATION postgres', t_name);
END
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION spa.create_tenant(character varying)
OWNER TO postgres;
If I run this function inside pgAdmin like this it's working fine:
select spa.create_tenant('somename');
Now I'm trying to run this function from my service like this:
#Override
#Transactional
public void createSchema(String name) {
StoredProcedureQuery sp = em.createStoredProcedureQuery("spa.create_tenant");
sp.registerStoredProcedureParameter("t_name", String.class, ParameterMode.IN);
sp.setParameter("t_name", name);
sp.execute();
}
If I run my method I'm getting following error:
javax.persistence.PersistenceException: org.hibernate.MappingException: No Dialect mapping for JDBC type: 1111
I'm guessing this is because of return type void that is defined in function so I changed return type to look like this:
RETURNS character varying AS
If I run my method again I'm getting this exception instead:
javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Error calling CallableStatement.getMoreResults
Does anyone know what is going on here and how to properly call stored procedures in PostgreSQL even with void as return type?
In case you are using also spring data, you could just define a procedure inside your #Repository interface like this,
#Procedure(value = "spa.create_tenant")
public void createTenantOrSomething(#Param("t_name") String tNameOrSomething);
More in the docs.
In your entity class, define a NamedNativeQuery like you would call postgresql function with select.
import javax.persistence.NamedNativeQueries;
import javax.persistence.NamedNativeQuery;
import javax.persistence.Entity;
#NamedNativeQueries(
value={
// cast is used for Hibernate, to prevent No Dialect mapping for JDBC type: 1111
#NamedNativeQuery(
name = "Tenant.createTenant",
query = "select cast(create_tenant(?) as text)"
)
}
)
#Entity
public class Tenant
hibernate is not able to map void, so a workaround is to cast result as text
public void createSchema(String name) {
Query query = em.createNamedQuery("Tenant.createTenant")
.setParameter(1, name);
query.getSingleResult();
}
Since you're using PostgreSQL, you can, as you've already written, call any stored procedure of type function in SELECT (Oracle, otherwise, would let you only execute functions declared to be read only in selects).
You can use EntityManager.createNativeQuery(SQL).
Since you're using Spring, you can use SimpleJdbcTemplate.query(SQL) to execute any SQL statement, as well.
I think it's the RETURN VOID that's causing the issue. So, changed the FUNCTION definition like this:
CREATE OR REPLACE FUNCTION spa.create_tenant(t_name character varying)
RETURNS bigint AS
$BODY$
BEGIN
EXECUTE format('CREATE SCHEMA IF NOT EXISTS %I AUTHORIZATION postgres', t_name);
RETURN 1;
END
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
ALTER FUNCTION spa.create_tenant(character varying)
OWNER TO postgres;
After you changed your function to return some dummy value, change the stored procedure query to this:
StoredProcedureQuery query = entityManager
.createStoredProcedureQuery("spa.create_tenant")
.registerStoredProcedureParameter(1,
Long.class, ParameterMode.OUT)
.registerStoredProcedureParameter(2,
String.class, ParameterMode.IN)
.setParameter(2, name);
query.getResultList();
If you want to keep it simple, just do this:
em.createSQLQuery("SELECT * FROM spa.create_tenant(:t_name) ")
.setParameter("t_name", name)").list();
Notice I used list() intentionally.. for some reason .update() didn't work for me.
PostgreSQL
Hibernate
Kotlin
CREATE OR REPLACE FUNCTION your_procedure() RETURNS text AS $$
BEGIN
RETURN 'Some text';
END;
$$ LANGUAGE plpgsql;
val query = session.createNativeQuery("SELECT your_procedure()")
query.list().map {
println("NativeQuery: $it")
}
For a procedure, try this:
#Procedure("spa.create_tenant")
String createTenant(String tenant);

Call Oracle Stored procedure from JDBC with complex Input and Output type

I'm so close in solving this question but I'm apparently missing something. My requirement is to call a stored procedure in Oracle from JDBC. The stored procedure takes 1 user-defined Oracle object as INput and another user-defined Oracle object as OUTput. The INput and OUTput objects have mix of both primitive Oracle data types and collection of another set of user-defined objects. I'm successfully able to call the stored procedure and get results back as long as I set NULL for the collection types in the INput and OUTput objects. If I try to create ArrayDescriptor for the list of Oracle objects to send it to the stored procedure I keep hitting roadblocks. So I need help with figuring out how to set the Array to the INput object and set that to CallableStatement. Please note, I am aware of how I can send the primitive type and array as direct inputs to the stored procedure. But I do not want to go that way as we later have to send 10 additional fields to the procedure, I do not want to add them to method signature. Here's the list of classes. Also, there is no compilation errors for the code below.
Package in oracle:
CREATE OR REPLACE PACKAGE testPkg AS
PROCEDURE spGetTestData (
TESTDATA_IN IN TESTDATA_IN_OBJ,
TESTDATA_OUT OUT TESTDATA_OUT_OBJ
);
END;
INput object for the stored procedure:
CREATE OR REPLACE TYPE TESTDATA_IN_OBJ AS OBJECT(
testStr1 VARCHAR2(5),
arrObj1 ARR_OBJ_1_NT);
Array Object as part of INput Object:
create or replace TYPE ARR_OBJ_1_NT AS TABLE OF ARR_OBJ_1_OBJ;
UserDefined Object part of INput Object:
CREATE OR REPLACE TYPE ARR_OBJ_1_OBJ AS OBJECT
(
teststr VARCHAR2(14),
testNumber NUMBER(4),
);
TestDataINObj.java:
import java.sql.Array;
import java.sql.SQLData;
import java.sql.SQLException;
import java.sql.SQLInput;
import java.sql.SQLOutput;
public class TestDataINObj implements SQLData
{
private String sql_type = "TESTDATA_IN_OBJ";
protected String testStr1;
protected Array arrObj1;
#Override
public String getSQLTypeName() throws SQLException
{
return this.sql_type;
}
// getter and setter for fields
#Override
public void readSQL(SQLInput stream, String typeName) throws SQLException
{
this.sql_type=typeName;
this.testStr1 = stream.readString();
this.arrObj1 = stream.readArray();
}
#Override
public void writeSQL(SQLOutput stream) throws SQLException
{
stream.writeString(this.testStr1);
stream.writeArray(this.arrObj1);
}
}
TestDataINObjConverter.java:
public class TestDataINObjConverter
{
public static TestDataINObj convertPOJOToDBInObj(Connection connection)
throws SQLException
{
TestDataINObj testDataINObj = new TestDataINObj();
testDataINObj.setTestStr1("some string");
ArrObj1NT[] ArrObj1NTList = ArrObj1NTConverter.convertPOJOToDBObj(); // this will return Java array of ArrObj1NT class
testDataINObj.setArrObj1(getOracleArray("ARR_OBJ_1_NT",connection, ArrObj1NTList));
return testDataINObj;
}
private static Array getOracleArray(final String typeName, Connection connection, ArrObj1NT[] ArrObj1NTList) throws SQLException
{
if (typeName == null)
{
return null;
}
Array oracleArray = new ARRAY(new ArrayDescriptor(typeName, connection), connection, ArrObj1NTList);
return oracleArray;
}
Code that actually executes call to stored procedure:
... //code to get connection
..// connection is of type T4CConnection
Map typeMap = connection.getTypeMap();
typeMap.put("TESTDATA_IN_OBJ", TestDataINObj.class);
typeMap.put("TESTDATA_OUT_OBJ", TestDataOUTObj.class);
typeMap.put("ARR_OBJ_1_NT", ArrObj1NT.class);
TestDataINObj testDataINObj = TestDataINObjConverter.convertPOJOToDBInObj(connection);
getMetaDataCallableStatement = connection.prepareCall("begin " + "testPkg" + ".spGetTestData (?,?);"+ " end;");
getMetaDataCallableStatement.setObject(1, testDataINObj);
getMetaDataCallableStatement.registerOutParameter(2, Types.STRUCT, "TESTDATA_OUT_OBJ");
rs = getMetaDataCallableStatement.executeQuery();
TestDataOUTObj testDataOUTObj = (TestDataOUTObj) getMetaDataCallableStatement.getObject(2, typeMap);
Miscellaneous:
1. The objects are declared in Schema level and is available for the db user to access it.
2. I've not included all of the corresponding Java objects here as it will take more space. They implement SQLData interface and their type names match with DB names. The read and writeSQL methods uses getString, getArray and corresponding setter methods.
This is a very old approach, why are you not using "Oradata" and "Oradatum" interface?
It will save lot of effort.
Your approach leaves a lot of scopr for error, you will have to read the stream in proper manner and check for ordering of fields yourself which can be tricky. Oradata approach will do that for you.
Coming to your approach, Your code is not very clear.
But just to give an overview, StructDescriptor will map to oracle record type and ArrayDescriptor will map to oracle table type, from your code i am confused about whta you are trying to achieve.
I can help if you can make it more clear.

Reading a BLOB using JDBC Spring without a result set

I have an Oracle stored procedure that returns a BLOB in an output parameter:
PROCEDURE GET_IMAGE_DATA(i_image_type IN NUMBER, o_image_data OUT BLOB) IS
BEGIN
SELECT IMAGE_DATA
INTO o_image_data
FROM IMAGES
WHERE IMAGE_TYPE = i_image_type;
END GET_IMAGE_DATA;
I want to use JDBC Spring to read this data. However, DefaultLobHandler (and I think OracleLobHandler) getBlobAsBytes() requires a resultset.
private static class QueryForBinaryCryptKey extends StoredProcedure {
private static final String SQL = "IMAGE_PKG.GET_IMAGE_DATA";
private DefaultLobHandler lobHandler;
QueryForImageData(DataSource dataSource) {
super(dataSource, SQL);
setFunction(false);
lobHandler = new DefaultLobHandler();
declareParameter(new SqlParameter(KEY_TYPE, OracleTypes.NUMBER));
declareParameter(new SqlOutParameter(KEY_BLOB, OracleTypes.BLOB));
}
public Map getImage(int keyType) {
Map outParams = super.execute(inParams(keyType));
//how can I get the contents of the blob right here since
//getBlobAsBytes requires a resultSet???
return outParams;
}
private Map inParams(int keyType) {
Map params = new HashMap();
params.put(KEY_TYPE, new Integer(keyType));
return params;
}
}
How can I get the blob data when all I have is an out parameter and not a resultset?
The JDBC Spring API (DefaultLobHandler and OracleLobHandler) require a ResultSet object for their BLOB related methods.
You need to convert your GET_IMAGE_DATA procedure into a function:
FUNCTION ATTACHMENT_BLOB_GET(IN_IMAGE_TYPE IN IMAGES.IMAGE_TYPE%TYPE)
RETURN SYS_REFCURSOR AS
results_cursor SYS_REFCURSOR;
BEGIN
OPEN results_cursor FOR
SELECT t.image_data
FROM IMAGES t
WHERE t.image_type = IN_IMAGE_TYPE;
RETURN results_cursor;
END;
OUT parameters are always good for some grief, BLOBs especially.
It is indeed possible to read Blob as Stream/byte[] without a ResultSet. Check this one out.

Resources