Spring/Hibernate tier called from Java Stored Procedure
Here is my scenario.
Building out a new physical model alongside an old db.
Two schema's inside same Oracle instance.
We are building a new Java tier on top of the new schema using spring/hibernate.
To maintain sync with the old db we are building a load of PLSQL code that will be called by PLSQL stored procs on the old schema.
====
Now it occurred to me that if I could put a copy of my new java tier in the database itself then the trigger code on the old schema could call a java stored proc wrapper which in turn called into my new java tier inside the instance.
This way I avoid duplication business logic in the db sync and the java middle tier. Basically I do away with the PLSQL sync code and just use the new java component.
This clearly has advantages from an automated testing point of view too.
So very interested in how/if anyone has made this work.
Potential issues...
- JVM version (outside the db we use Sun Java 5 - inside the db I'm not sure what is used).
- How would spring access it's config files?
user563578,
You asked:
interested in how/if anyone has made this workNot me.
You also asked:
Potential issues...
- JVM version (outside db use Sun Java 5 - inside db not sure)
- How would spring access it's config files?
Oracle has its own JVM embedded in the database: OJVM
In Oracle 8i it is compatible with JDK 1.2
In Oracle 9i it is comaptible with JDK 1.3
In Oracle 10g it is compatible with JDK 1.4
You can access files outside of the database from OJVM, you just need to set correct permissions.
Perhaps Kuassi Mensah's book, Oracle Database Programming Using Java and Web Services will be of help?
Good Luck,
Avi.
Similar Messages
-
Calling external servlet from java stored procedure
Hello,
I need to call an external servlet which is in 9iAS server ( unix box) from Java Stored procedure in oracle database.
Can anybody give me an idea? is it possible?
Thanks,
ViswaI am trying the same. Here is URL which will help u.
http://otn.oracle.com/sample_code/tech/java/jsp/samples/wsclient/Readme.html
Let me know when you run servlet successfully.
Regards
Satish -
How to call EJB deployed on OC4J from java stored procedure?
Hello,
I'd like to call EJB from java stored procedure. My example works fine from command line, but the problem seems to be with deployment of this code into database. Especialy I'm wondering how to reference jars like oc4jclient.jar, ejb.jar, ... from java stored procedure.
Is there some example how to do that ?
Can You help me please ?
Many thanks,
Radim Kolek,
Eurotel Prague.Hi,
You may want to check up this thread
Calling JBoss EJBs from Java stored procedure
Hope this helps,
Sujatha.
OTN Group. -
Executing batch file from Java stored procedure hang
Dears,
I'm using the following code to execute batch file from Java Stored procedure, which is working fine from Java IDE JDeveloper 10.1.3.4.
public static String runFile(String drive)
String result = "";
String content = "echo off\n" + "vol " + drive + ": | find /i \"Serial Number is\"";
try {
File directory = new File(drive + ":");
File file = File.createTempFile("bb1", ".bat", directory);
file.deleteOnExit();
FileWriter fw = new java.io.FileWriter(file);
fw.write(content);
fw.close();
// The next line is the command causing the problem
Process p = Runtime.getRuntime().exec("cmd.exe /c " + file.getPath());
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = input.readLine()) != null)
result += line;
input.close();
file.delete();
result = result.substring( result.lastIndexOf( ' ' )).trim();
} catch (Exception e) {
e.printStackTrace();
result = e.getClass().getName() + " : " + e.getMessage();
return result;
The above code is used in getting the volume of a drive on windows, something like "80EC-C230"
I gave the SYSTEM schema the required privilege to execute the code.
EXEC DBMS_JAVA.grant_permission('SYSTEM', 'java.io.FilePermission', '<<ALL FILES>>', 'read ,write, execute, delete');
EXEC DBMS_JAVA.grant_permission('SYSTEM', 'SYS:java.lang.RuntimePermission', 'writeFileDescriptor', '');
EXEC DBMS_JAVA.grant_permission('SYSTEM', 'SYS:java.lang.RuntimePermission', 'readFileDescriptor', '');
GRANT JAVAUSERPRIV TO SYSTEM;
I have used the following to load the class in Oracle 9ir2 DB:
loadjava -u [system/******@orcl|mailto:system/******@orcl] -v -resolve C:\Server\src\net\dev\Util.java
CREATE FUNCTION A1(drive IN VARCHAR2) RETURN VARCHAR2 AS LANGUAGE JAVA NAME 'net.dev.Util.a1(java.lang.String) return java.lang.String';
variable serial1 varchar2(1000);
call A1( 'C' ) into :serial1;
The problem that it hangs when I execute the call to the function (I have indicated the line causing the problem in a comment in the code).
I have seen similar problems on other forums, but no solution posted
[http://oracle.ittoolbox.com/groups/technical-functional/oracle-jdeveloper-l/run-an-exe-file-using-oracle-database-trigger-1567662]
I have posted this in JDeveloper forum ([t-853821]) but suggested to post for forum in DB.
Can anyne help?Dear Peter,
You are totally right, I got this as mistake copy paste. I'm just having a Java utility for running external files outside Oracle DB, this is the method runFile()
I'm passing it the content of script and names of file to be created on the fly and executed then deleted, sorry for the mistake in creating caller function.
The main point, how I claim that the line in code where creating external process is the problem. I have tried the code with commenting this line and it was working ok, I made this to make sure of the permission required that I need to give to the schema passing security permission problems.
The function script is running perfect if I'm executing vbs script outside Oracle using something like "cscript //NoLogo aaa1.vbs", but when I use the command line the call just never returns to me "cmd.exe /c bb1.bat".
where content of bb1.bat as follows:
echo off
vol C: | find /i "Serial Number is"
The above batch file just get the serial number of hard drive assigned when windows formatted HD.
Same code runs outside Oracle just fine, but inside Oracle doesn't return if I exectued the following:
variable serial1 varchar2(1000);
call A1( 'C' ) into :serial1;
Never returns
Thanks for tracing teh issue to that details ;) hope you coul help. -
Out of memory error when calling a java stored procedure multiple times
Trying to run a PL/SQL loop calling a java stored procedure, I get the following error:
"ORA-04030: out of process memory when trying to allocate 262188 byte callheap,ioc_allocate free)"
(with some other error lines).
The stored procedure does two major things:
1) Open a socket to communicate with a server, of which it queries some data.
2) Use JDBC (with the default DB connection it has, as a stored procedure) to write the results to a table.
All socket connections, statements, etc. are properly closed and all memory should be garbage collected between each call.
Can anyone offer an explanation or additional checks to make? I'm quite sure the code isn't causing the problem, since I've tried running it as a stand alone application (outside of Oracle) and didn't have any problems.
Thanks.Hi,
Verify that the database parameters are set correctly.
EA -
Execution Times of Stored Procedures Called from Other Stored Procedures
If I execute sys.dm_exec_procedure_stats, it will produce execution times of my stored procedures executed recently.
However, stored procedures called from other stored procedures do not show up.
Is there code that can return the execution times of stored procedures even though they are called from other stored procedures.Look at the example. It is counting nested execution.
CREATE PROC z1SP AS SELECT * FROM Production.Product;
GO
CREATE PROC z2SP AS SELECT * FROM Production.Product WHERE Color is not null; EXEC z1SP;
GO
SELECT object_name(2002822197), object_name(2034822311);
--z1SP z2SP
EXEC z1SP; EXEC z2SP;
GO 10
SELECT * from sys.dm_exec_procedure_stats
database_id object_id type type_desc cached_time last_execution_time execution_count
16 2002822197 P SQL_STORED_PROCEDURE 2014-12-16 13:02:45.170 2014-12-16 13:02:46.717 20
16 2034822311 P SQL_STORED_PROCEDURE 2014-12-16 13:02:45.460 2014-12-16 13:02:46.687 10
Kalman Toth Database & OLAP Architect
SQL Server 2014 Database Design
New Book / Kindle: Beginner Database Design & SQL Programming Using Microsoft SQL Server 2014 -
Return national language strings from java stored procedures
Hi, all.
How does i can return String which contains national characters from java stored procedure? I.e. convert UTF java string to national language of database. It's does not processing automatically (why?).
declaration of procedure:
CREATE OR REPLACE FUNCTION TestNLSString RETURN VARCHAR2
AS
LANGUAGE JAVA
NAME 'test.SomeClass.getNLSString() return java.lang.String';
SELECT TestNLSString AS X FROM DUAL;
X
iiiii
OS: Windows 2000 Server
Oracle Server version: Oracle 8.1.7.1.4Ok. I had a specific problem.
I want to use java stored procedure (function) to make a connection to remote db using supplied connection parameters make some quieries there end return results in a form of structured data - object.
I have defined an object type in a database where the function will reside. I granted execute privilege to public user on this type, made public synonyms to both, the object type and the function, so anybody connected to the same database would have an access to this functionality.
I supposed that if I supply connection parameters for some other user but the same database when running the function, everything should go smooth. Yeah.
My java code executed ok: it made a connection to the db with some x user, it resolved object type descriptor given (oracle.sql.StructDescriptor), but pl/sql wrapper function reported the error I've mentioned. If I executed the function giving it the connection parameters for same account as where object type was declared, everything went fine.
My final solution is:
Make TWO! connection in java code: 1st for ("jdbc:default:connection:"), 2nd for remote database account.
Use first connection to construct oracle.sql.StructDescriptor
Use second connection to retreive data from remote db -
No output from java stored procedure
Hi all,
I'm calling my java stored procedure as follows. In my java code I have several System.out.println statements, but none of them are displayed.
Any suggestions or explanations?
Thanks,
Melani
spool $ORACLE_BASE/local/logs/execjava_prod.log
set timing on
SET SERVEROUTPUT ON SIZE 5000
CALL dbms_java.set_output(5000);
variable i varchar2(12)
call getDatesAndLoad('/dbs/TEST/105pd.dmd') into :i;
print i
spool offIn the link you referenced, it says
As a result, System.out and System.err print to the current trace files. To redirect output to the SQL*Plus text buffer, call the procedure set_output() in package DBMS_JAVA, as follows:
SQL> SET SERVEROUTPUT ON
SQL> CALL dbms_java.set_output(2000);
Which is what I have done. So then shouldn't my output be redirected to the sqlplus text buffer? -
Calling XML API's from Java Stored Procedures in DB
Hi,
I am have and Oracle 10gR2 db installed and XML Publisher Enterprise Server 5.6.2.
I have created the following Java Class and used loadjava to make it a Java Stored Procedure:
<code>
import java.io.IOException;
import java.lang.Object;
import oracle.apps.xdo.XDOException;
import oracle.apps.xdo.template.FOProcessor;
import oracle.apps.xdo.template.RTFProcessor;
public class callingXMLP{
public static String rtfToXsl(String rtfFile, String xslFile)
try {
RTFProcessor rtfProcessor = new RTFProcessor(rtfFile); //Input RTF
rtfProcessor.setOutput(xslFile);
rtfProcessor.process();
} catch (IOException IOE) {
return" Error "+IOE.getMessage();}
catch(XDOException XDE ){
return" Error "+XDE.getMessage();
return "Success";
public static String mergeXmlXsl(String xmlFile, String xslFile, String outputFile)
FOProcessor processor = new FOProcessor();
processor.setData(xmlFile); //Input XML File
processor.setTemplate(xslFile); //Input XSL File
processor.setOutput(outputFile); //Ouput File
processor.setOutputFormat(FOProcessor.FORMAT_PDF);
//start processing
try {
processor.generate();
catch (XDOException e){
e.printStackTrace();
//System.exit(1);
return "Error - "+e.getMessage();
//System.exit(0);
return "Success";
</code>
I then wrap this using the following function spec in pl/sql:
create or replace function callXMLP(input1 VARCHAR2, output1 VARCHAR2) RETURN VARCHAR2
as language java name 'callingXMLP.rtfToXsl(java.lang.String,java.lang.String) return java.lang.String';
and
create or replace function mergeXMLXSL(xml VARCHAR2, xsl VARCHAR2, output VARCHAR2) RETURN VARCHAR2
as language java name 'callingXMLP.mergeXmlXsl(java.lang.String,java.lang.String,java.lang.String) return java.lang.String';
Calling the callXMLP function works fine, and produces an XSL file from the input RTF file as expected.
When I run the mergeXMLXSL function, it says that the function has completed successfully, but it seems to be throwing an XDOException error as it is returning "Error - null" message from the Java.
A PDF document is being created, but it does not have any content. I have also modified the Java to create an RTF instead, but still the same thing happens.
Is there anything that I need to check, or something that I am missing when trying to create the final PDF document?
Please help, I am completely stuck with this now.
Many Thanks,
CjHello Chris,
I have been able to create a PDF from the database. I loaded the following jar files and removed any java class that could not compile.
activation.jar, axis-ant.jar, axis.jar, axis-schema.jar, bicmn.jar, bipres.jar, collections.jar,
commons-beanutils.jar, commons-collections-3.1.jar, commons-collections.jar, commons-dbcp-1.1.jar commons-digester.jar, commons-discovery.jar, commons-el.jar, commons-fileupload.jar, commons-logging-api.jar commons-logging.jar, commons-pool-1.1.jar, http_client.jar, i18nAPI_v3.jar, javamail.jar, jaxrpc.jar,
jewt4.jar, jsp-el-api.jar, log4j-1.2.8.jar, logkit-1.2.jar, ojpse.jar, oracle-el.jar, oraclepki.jar,
orai18n.jar, quartz-1.5.1.jar, quartz-oracle-1.5.1.jar, regexp.jar, saaj.jar, service-gateway.jar, share.jar, uix2.jar, uix2tags.jar, versioninfo.jar, wsdl4j.jar, xdocore.jar, xdoparser.jar, xdo-server-delivery-1.0-SNAPSHOT.jar, xdo-server-kernel-0.1.jar, xdo-server-kernel-impl-0.1.jar, xdo-server-scheduling-1.0-SNAPSHOT.jar, xercesImpl.jar, xmlparserv2-904.jar, xmlpserver.jar, xsu12.jar
I needed to copy the XML Publisher fonts to the database server and ran the following java grants, note my $ORACLE_HOME is /opt/app/oracle/product/10.1.0/
dbms_java.grant_permission('XMLP', 'java.util.PropertyPermission', '*', 'read,write');
dbms_java.grant_permission('XMLP', 'java.net.SocketPermission', '*', 'connect, resolve');
dbms_java.grant_permission('XMLP', 'java.io.FilePermission', '/tmp/*', 'read, write, delete');
dbms_java.grant_permission('XMLP', 'java.io.FilePermission', '/opt/app/oracle/product/10.1.0/javavm/lib/*', 'read');
dbms_java.grant_permission('XMLP', 'java.io.FilePermission', '/opt/app/oracle/product/10.1.0/javavm/lib/fonts/*', 'read');
dbms_java.grant_permission('XMLP', 'java.lang.RuntimePermission', 'setFactory', '');
George -
Using JNDI from Java Stored Procedures
Hi,
we want to call external services (mostly via middle tier/J2EE) from within the database (9i Rel. 2) using Java Stored Procedures and JNDI.
Does anybody have some hints/samples how to do this? Will we have to use oc4jclient.jar? If yes, how? Where can I find some more detailed documentation?
Lot's of questions...
Thank
MatthiasUh, not JNI but JNDI you asked. And use of JNI should be generally discouraged unless there is absolutely no other way (like co-located CORBA code for decoupling+speed). Can you direct me to a HOW-TO Oracle DB JVM configuration page? I want to know how to configure the internal DB JVM in a hurry.
Thank you,
Bryan -
How to execute a procedure or function from Java Stored procedure
Hi,
I am new to Java Stored Procedures. I am working on Oracle 8i and JVM 1.3.1. I want to call a PL/SQL procedure from within Java. I have tried looking at severa; cources but they are quite high level for me. Can someone provide a simple example including the Source Code for .java file and also the calling function's code?
Heres a sample of what I have been working on: I an including Java code, and Function code and how I call the function. Instead of doing "select sysdate from dual" I want to do like "create table temp1(var1 varchar2(10))" or similar... like "exec procname(var1)" etc.
Thanks in advance.
PS. The variable passed in function is just a dummy variable.
-----Begin Java code-------
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.ResultSet;
//Oracle Extensions to JDBC
import oracle.jdbc.driver.OracleDriver;
public class Test2{
public static String Testing(String d) {
Connection connection = null; // Database connection object
try {
// Get a Default Database Connection using Server Side JDBC Driver.
// Note : This class will be loaded on the Database Server and hence use a
// Se[i]Long postings are being truncated to ~1 kB at this time.what your after is
Connection conn = DriverManager.getConnection
("jdbc:oracle:oci:@<hoststring>", "scott", "tiger");
CallableStatement cs = conn.prepareCall ("begin ? := foo(?); end;");
cs.registerOutParameter(1,Types.CHAR);
cs.setString(2, "aa");
cs.executeUpdate();
String result = cs.getString(1);
a more complete description can be found in the documentation at
http://download-west.oracle.com/docs/cd/B10501_01/java.920/a96654/basic.htm#1001934
Dom -
SQLException: Cursor is closed while calling a java stored procedure
Hi,
I got the following error when trying to read from a cursor of a java stored procedure:
java.sql.SQLException: Cursor is closed
The java procedure is stored in the database and wrapped by a sql call. Then another java class executes the sql call.
The stored procedure looks like this:
import java.io.Reader; import java.security.MessageDigest; import java.sql.*; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import oracle.jdbc.OracleCallableStatement; import oracle.jdbc.OracleConnection; public class test { static Connection conn = null; static String username = null; static String password = null; static Integer userid = null; public static void main(String args[]) throws Exception { username = "keller"; password = "945435"; login(username, password); } public static String login(String in_username, String in_password) { String access = null; String password = null; try { DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); // Non OracleVM System.out.print("Verbindung wird initialisiert... "); conn = //DriverManager.getConnection("jdbc:default:connection:"); //conn.setAutoCommit(false); DriverManager.getConnection("jdbc:oracle:thin:@[...]:1521:[...]","[...]","[...]"); System.out.println("OK"); System.out.print("Logindaten werden ueberprueft... "); String sql = "SELECT matrikelnr, password FROM student WHERE name = ?"; PreparedStatement pstmt = conn.prepareStatement(sql); pstmt.setString(1, in_username); ResultSet rset = pstmt.executeQuery(); while (rset.next()) { userid = rset.getInt(1); password = rset.getString(2); } access = "student"; pstmt = conn.prepareStatement(sql); if (password == null) { sql = "SELECT dozentnr, password FROM dozent WHERE name = ?"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, in_username); rset = pstmt.executeQuery(); while (rset.next()) { userid = rset.getInt(1); password = rset.getString(2); } pstmt = conn.prepareStatement(sql); if (password == null) { throw new SQLException("User nicht gefunden!"); } access = "dozent"; } //rset.close(); // Resultset schließen //pstmt.close(); // Statement schließen // MD5 Hash vergleichen MessageDigest md5 = MessageDigest.getInstance("MD5"); md5.reset(); md5.update(in_password.getBytes()); byte[] result = md5.digest(); StringBuffer hexString = new StringBuffer(); for (int i=0; i<result.length; i++) { if(result[i] <= 15 && result[i] >= 0){ hexString.append("0"); } hexString.append(Integer.toHexString(0xFF & result));
if (password != null) {
if (password.equals(hexString.toString())) {
System.out.println("OK");
} else {
throw new Exception("Falsches Passwort!");
catch(SQLException e) {
System.err.println("SQL Fehler!");
System.err.println(e.getMessage());
catch(Exception e) {
System.err.println("Fehler!");
System.err.println(e.getMessage());
return access;
public static void getLeistungsschein(int matrikelnr, ResultSet[] rout)
ResultSet rs = null;
try
System.out.print("Berechtigung ueberpruefen... ");
if (userid != matrikelnr)
throw new Exception("Zugriff verweigert, keine Berechtigung!");
int mnr = matrikelnr;
((OracleConnection)conn).setCreateStatementAsRefCursor(true);
PreparedStatement ps = conn.prepareStatement("select bezeichnung, note from klausur inner join leistungsschein on klausur.KLAUSURNR=leistungsschein.KLAUSURNR where matrikelnr= ?");
ps.setInt(1, mnr);
rs = (ResultSet)ps.executeQuery();
rout[0]= rs;
catch(SQLException e) {
System.err.println("Fehler!");
System.err.println(e.getMessage());
catch(Exception e) {
System.err.println("Fehler!");
System.err.println(e.getMessage());
The sql call:
create or replace
procedure pgetleistungsschein(matrikelnr in number, cur OUT refcurpkg.refcur_t) is
language java name 'Klausurverwaltung.getLeistungsschein(int, java.sql.ResultSet[])';
And finally the wrapper is called by another java programm, see this:
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import oracle.jdbc.OracleCallableStatement;
import oracle.jdbc.OracleResultSet;
import oracle.jdbc.OracleTypes;
public class cursortest {
public static void main(String[] args) {
try{
//-- Oracle Treiber laden
Class.forName( "oracle.jdbc.driver.OracleDriver" );
Connection c = DriverManager.getConnection( "jdbc:oracle:thin:@sligo.fh-trier.de:1521:ubuntu", "dbsem_java","javajava");
CallableStatement stmt = null;
ResultSet rs1 = null;
int matrnr = 945098;
// Call PLSQL Stored Procedure
stmt = (CallableStatement)c.prepareCall("{ call ? := getklausuren(?) }");
stmt.setInt(2, matrnr);
// 2nd parameter is OUT paremeter
stmt.registerOutParameter(1, OracleTypes.CURSOR);
// Execute the callable statement
stmt.execute();
//Cursor in ResultSet einlesen
rs1 = ((OracleCallableStatement)stmt).getCursor(1);
ResultSetMetaData rsmd = rs1.getMetaData();
int anzSpalten = rsmd.getColumnCount();
List<String[]> zeilen = new ArrayList<String[]>();
while(rs1.next())
String[] zeile = new String[anzSpalten];
for (int i=1; i<=anzSpalten; i++)
zeile[i-1]=rs1.getString(i);
zeilen.add(zeile);
String[][] array_angeb_klaus = (String[][])zeilen.toArray(new String[zeilen.size()][anzSpalten]);
//**** ENDE
rs1.close();
stmt.close();
//c.close();
catch (SQLException e){
System.out.println(e);
catch (ClassNotFoundException f){
System.out.println(f);On top of what jschell says, this just looks wrong in terms of how Oracle's internal Java works as well.
[Have a look here |http://www.oracle.com/technology/sample_code/tech/java/codesnippet/jdbc/refcur/index.html] (unless things have changed significantly over the past few years for Oracle Java).
Is the db you are querying a different one to the one this Java is stored in? -
ResultSet from Java Stored Procedures
Hi,
How do I obtain a resultset from a Java Stored Procedure?
My stored procedure, deployed in Oracle8i, has Database package as sample.Have published setConnection() and getDept() methods.
Code for Java Stored Procedure:
package SPPackage;
import java.sql.*;
public class StoredProcApplication {
protected static Connection connection = null;
protected static Statement stmt = null;
protected static ResultSet res = null;
public static void setConnection() throws SQLException {
connection = new oracle.jdbc.driver.OracleDriver().defaultConnection();
public static void getDept(Object[] obj) throws SQLException {
if (connection == null) {
setConnection();
if (stmt == null) {
stmt = connection.createStatement();
if (res == null) {
res = stmt.executeQuery("select * from DEPT");
obj[0] = res;
Code for TesterApplication :
package SPPackage;
import java.sql.*;
public class TesterApplication {
private static final String URL = "jdbc:oracle:thin:@sandeep:1521:oracle8i";
private static final String userId = "sandeep";
private static final String password = "sandeep";
private Connection connection;
private CallableStatement stmt;
private ResultSet res;
public void setConnection() throws ClassNotFoundException,SQLException {
Class.forName("oracle.jdbc.driver.OracleDriver");
connection = DriverManager.getConnection(URL,userId,password);
public void getResultFromSP() throws SQLException {
//prepare to call the stored procedure
stmt = connection.prepareCall("{call sample.getDept(?)}");
//register the OUT parameters
stmt.registerOutParameter(1,Types.OTHER);
//execute the query
stmt.execute();
ResultSet res = (ResultSet)stmt.getObject(1);
while (res.next()) {
System.out.print(res.getInt(1) + " | " );
System.out.print(res.getString(2) + " | " );
System.out.print(res.getString(3) + " \n " );
public TesterApplication() throws SQLException,ClassNotFoundException {
try {
setConnection();
getResultFromSP();
} finally {
if (res != null) { res.close(); res = null; }
if (stmt != null) { stmt.close(); stmt = null; }
if (connection != null) { connection.close(); connection = null; }
public static void main(String[] args) {
try {
TesterApplication ta = new TesterApplication();
} catch (Exception e) {
System.err.println("Error while executing stored procedure " + e.getMessage());
e.printStackTrace();
When I run the TesterApplication, I get the following exception :
java.sql.SQLException: Invalid column type: get_internal_type
at oracle.jdbc.dbaccess.DBError.check_error(Compiled Code)
at oracle.jdbc.driver.OracleStatement.get_internal_type(Compiled Code)
at oracle.jdbc.driver.OracleCallableStatement.registerOutParameter(Compiled Code)
Also, if I want to execute the ResultSet in the stored proc itself, and return the values as Arrays of int[], and String[], how do I do it?By default the you can populate only int[0], String[0] , i.e. only one value!!!
if my statement is unknown, i.e, it might return a combination of updates and resultsets, how do I go about processing the result?
Please advise!!
TIA
Sandeep
nullHi kkirk,
I found the post you mentioned.Well it dates back to November 1999 - "Problem returning resultset or ARRAY from java stored proc" by Stuart Popejoy ([email protected]).Too bad, it is still not solved!!
I am not very good at PL/SQL.However, it would still be helpful, if you could post the code here, or at my email address.
Meanwhile, I was trying this during the week-end.There seems to be a glimmer of hope!!
Let me know, if this makes sense :
CallableStatement cs = connection.prepareCall("begin open ? for select * from dept; end");
try {
cs.registerOutParameter(1,OracleTypes.CURSOR);
ResultSet res = ((OracleCallableStatement)cs).getCursor(1);
while (res.next()) {
//get the values
} catch (Exception e) {
e.printStacktrace();
However, I am getting an exception trace
Error while executing stored procedure Invalid column type: getLong
java.sql.SQLException: Invalid column type: getLong
at oracle.jdbc.dbaccess.DBError.check_error(Compiled Code)
at oracle.jdbc.driver.OracleStatement.getLongValue(Compiled Code)
Not quite sure why this is happening!!
TIA,
Sandeep
null -
Jena Adapter API access from Java Stored Procedures?
Is it possible to use Jena API from code in java stored procedures in Oracle DBMS 11gR2? Possible but not recommended?
The reason is that my company uses .Net as the application server plattform (not Java). Calling Java Stored Procedures from .Net is one way to use Jena library.
Thank you!
TrondHi Trond,
Unfortunately the sdordfclient.jar was compiled and built with JDK 6 and the JVM supported in the Oracle database 11gR2 is JDK5.
If you have a strong requirement, please file a SR against Oracle support. We will then look into a possible recompilation and
rebuild.
Thanks,
Zhe Wu -
Passing Tables back from Java Stored Procedures
Thomas Kyte has written (in reference to
trying to pass an array back from a stored
function call):
You can do one of two things (and both require the use of
objects). You cannot use PLSQL table types as JDBC cannot bind to
this type -- we must use OBJECT Types.
[snip]
Another way is to use a result set and "select * from
plsql_function". It could look like this:
ops$tkyte@8i> create or replace type myTableType as table of
varchar2 (64);
2 /
Type created.
ops$tkyte@8i>
ops$tkyte@8i>
ops$tkyte@8i> create or replace
2 function demo_proc2( p_rows_to_make_up in number )
3 return myTableType
4 as
5 l_data myTableType := myTableType();
6 begin
7 for i in 1 .. p_rows_to_make_up
8 loop
9 l_data.extend;
10 l_data(i) := 'Made up row ' | | i;
11 end loop;
12 return l_data;
13 end;
14 /
Function created.
ops$tkyte@8i>
ops$tkyte@8i> select *
2 from the ( select cast( demo_proc2(5) as mytableType )
3 from dual );
COLUMN_VALUE
Made up row 1
Made up row 2
Made up row 3
Made up row 4 [Image]
Made up row 5
So, your JDBC program would just run the query to get the data.
If the function "demo_proc2" cannot be called from SQL for
whatever reason (eg: it calls an impure function in another piece
of code or it itself tries to modify the database via an insert
or whatever), you'll just make a package like:
ops$tkyte@8i> create or replace package my_pkg
2 as
3
4 procedure Make_up_the_data( p_rows_to_make_up in
number ); 5 function Get_The_Data return myTableType;
6 end;
7 /
Package created.
ops$tkyte@8i>
ops$tkyte@8i> create or replace package body my_pkg
2 as
3
4 g_data myTableType;
5
6 procedure Make_up_the_data( p_rows_to_make_up in number )
7 as
8 begin
9 g_data := myTableType();
10 for i in 1 .. p_rows_to_make_up
11 loop
12 g_data.extend;
13 g_data(i) := 'Made up row ' | | i;
14 end loop;
15 end;
16
17
18 function get_the_data return myTableType
19 is
20 begin
21 return g_data;
22 end;
23
24 end;
25 /
Package body created.
ops$tkyte@8i>
ops$tkyte@8i> exec my_pkg.make_up_the_data( 3 );
PL/SQL procedure successfully completed.
ops$tkyte@8i>
ops$tkyte@8i> select *
2 from the ( select cast( my_pkg.get_the_data as mytableType
) 3 from dual );
COLUMN_VALUE
Made up row 1
Made up row 2
Made up row 3
And you'll call the procedure followed by a query to get the
data...
I have tried this, and it works perfectly.
My question, is what does the wrapper look
like if the stored function is written
in java instead of PL/SQL? My experiments
with putting the function in java have been
dismal failures. (I supposed I should also
ask how the java stored procedure might
look also, as I suppose that could be where
I have been having a problem)
nullThanks for the response Avi, but I think I need to clarify my question. The articles referenced in your link tended to describe using PL/SQL ref cursors in Java stored procedures and also the desire to pass ref cursors from Java to PL/SQL programs. Unfortunately, what I am looking to do is the opposite.
We currently have several Java stored procedures that are accessed via select statements that have become a performance bottleneck in our system. Originally the business requirements were such that only a small number of rows were ever selected and passed into the Java stored procedures. Well, business requirements have changed and now thousands and potentially tens of thousands of rows can be passed in. We benchmarked Java stored procedures vs. PL/SQL stored procedures being accessed via a select statement and PL/SQL had far better performance and scaleable. So, our thought is by decouple the persistence logic into PL/SQL and keeping the business logic in Java stored procedures we can increase performance without having to do a major rewrite of the existing code. This leads to the current problem.
What we currently do is select into a Java stored procedure which has many database access calls. What we would like to do is select against a PL/SQL stored procedure to aggregate the data and then pass that data via a ref cursor (or whatever structure is acceptable) to a Java stored procedure. This would save us a significant amount of work since the current Java stored procedures would simple need to be changed to not make database calls since the data would be handed to them.
Is there a way to send a ref cursor from PL/SQL as an input parameter to a Java stored procedure? My call would potentially look like this:
SELECT java_stored_proc(pl/sql_stored_proc(col_id))
FROM table_of_5000_rows;
Sorry for the lengthy post.
Maybe you are looking for
-
I dropped my iPhone 5s on CARPET and it died?
Guys, this is a sticky situation that myself nor my brother can come to. Today at approximately 1:20 p.m I dropped my iPhone 5s as it was sitting on my lap. With my headphones blasting, my iPhone diligently fell out of my lap and instantly, my music
-
BIOS-GPT grub cannot find the root device in LVM setup
Greetings Arch Linux Community, Recently I started my journey of installing Arch Linux on my VMware Workstation. I successfully installed the non-LVM instance not long before I noticed the advantages of LVM, then I just started a new Arch Linux setup
-
Dear Experts, I have an ICO configured scenario where sender is ECC and receiver is a 3rd party application (Sender IDOC_AAE-PI-SOAP asynchronous scenario). Idocs are stuck in SM58 of ECC, connection test of relevant RFC destination is successful. Er
-
FPM (floor plan manager) translations
Hi, does anyone of you know how to translate the configuration you made for the FPM component. The standard buttons are translated already (except for next and previous, they are hard coded, shame shame shame.) But if you add extra buttons I can't se
-
Hi SBS 2011 std. Is it OK to install windows 2008 R2 SP1? It appears in Windows Update. Can it be done remotely? Thanks Regards