Passing Array of java objects to and from oracle database-Complete Example

Hi all ,
I am posting a working example of Passing Array of java objects to and from oracle database . I have struggled a lot to get it working and since finally its working , postinmg it here so that it coudl be helpful to the rest of the folks.
First thinsg first
i) Create a Java Value Object which you want to pass .
create or replace and compile java source named Person as
import java.sql.*;
import java.io.*;
public class Person implements SQLData
private String sql_type = "PERSON_T";
public int person_id;
public String person_name;
public Person () {}
public String getSQLTypeName() throws SQLException { return sql_type; }
public void readSQL(SQLInput stream, String typeName) throws SQLException
sql_type = typeName;
person_id = stream.readInt();
person_name = stream.readString();
public void writeSQL(SQLOutput stream) throws SQLException
stream.writeInt (person_id);
stream.writeString (person_name);
ii) Once you created a Java class compile this class in sql plus. Just Copy paste and run it in SQL .
you should see a message called "Java created."
iii) Now create your object Types
CREATE TYPE person_t AS OBJECT
EXTERNAL NAME 'Person' LANGUAGE JAVA
USING SQLData (
person_id NUMBER(9) EXTERNAL NAME 'person_id',
person_name VARCHAR2(30) EXTERNAL NAME 'person_name'
iv) Now create a table of Objects
CREATE TYPE person_tab IS TABLE OF person_t;
v) Now create your procedure . Ensure that you create dummy table called "person_test" for loggiing values.
create or replace
procedure give_me_an_array( p_array in person_tab,p_arrayout out person_tab)
as
l_person_id Number;
l_person_name Varchar2(200);
l_person person_t;
l_p_arrayout person_tab;
errm Varchar2(2000);
begin
     l_p_arrayout := person_tab();
for i in 1 .. p_array.count
loop
     l_p_arrayout.extend;
     insert into person_test values(p_array(i).person_id, 'in Record '||p_array(i).person_name);
     l_person_id := p_array(i).person_id;
     l_person_name := p_array(i).person_name;
     l_person := person_t(null,null);
     l_person.person_id := l_person_id + 5;
     l_person.person_name := 'Out Record ' ||l_person_name ;
     l_p_arrayout(i) := l_person;
end loop;
p_arrayout := l_p_arrayout;
     l_person_id := p_arrayout.count;
for i in 1 .. p_arrayout.count
loop
insert into person_test values(l_person_id, p_arrayout(i).person_name);
end loop;
commit;
EXCEPTION WHEN OTHERS THEN
     errm := SQLERRM;
     insert into person_test values(-1, errm);
     commit;
end;
vi) Now finally create your java class which will invoke the pl/sql procedure and get the updated value array and then display it on your screen>Alternatively you can also check the "person_test" tbale
import java.util.Date;
import java.io.*;
import java.sql.*;
import oracle.sql.*;
import oracle.jdbc.driver.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class ArrayDemo
public static void passArray() throws SQLException
Connection conn = getConnection();
ArrayDemo a = new ArrayDemo();
Person pn1 = new Person();
pn1.person_id = 1;
pn1.person_name = "SunilKumar";
Person pn2 = new Person();
pn2.person_id = 2;
pn2.person_name = "Superb";
Person pn3 = new Person();
pn3.person_id = 31;
pn3.person_name = "Outstanding";
Person[] P_arr = {pn1, pn2, pn3};
Person[] P_arr_out = new Person[3];
ArrayDescriptor descriptor =
ArrayDescriptor.createDescriptor( "PERSON_TAB", conn );
ARRAY array_to_pass =
new ARRAY( descriptor, conn, P_arr);
OracleCallableStatement ps =
(OracleCallableStatement )conn.prepareCall
( "begin give_me_an_array(?,?); end;" );
ps.setARRAY( 1, array_to_pass );
     ps.registerOutParameter( 2, OracleTypes.ARRAY,"PERSON_TAB" );
     ps.execute();
     oracle.sql.ARRAY returnArray = (oracle.sql.ARRAY)ps.getArray(2);
Object[] personDetails = (Object[]) returnArray.getArray();
Person person_record = new Person();
for (int i = 0; i < personDetails.length; i++) {
          person_record = (Person)personDetails;
          System.out.println( "row " + i + " = '" + person_record.person_name +"'" );
                    public static void main (String args[]){
     try
                         ArrayDemo tfc = new ArrayDemo();
                         tfc.passArray();
     catch(Exception e) {
                    e.printStackTrace();
          public static Connection getConnection() {
     try
                         Class.forName ("oracle.jdbc.OracleDriver");
                         return DriverManager.getConnection("jdbc:oracle:thin:@<<HostNanem>>:1523:VIS",
                         "username", "password");
     catch(Exception SQLe) {
                    System.out.println("IN EXCEPTION BLOCK ");
                    return null;
and thats it. you are done.
Hope it atleast helps people to get started. Comments are appreciated. I can be reached at ([email protected]) or [email protected]
Thanks
Sunil.s

Hi Sunil,
I've a similar situation where I'm trying to insert Java objects in db using bulk insert. My issue is with performance for which I've created a new thread.
http://forum.java.sun.com/thread.jspa?threadID=5270260&tstart=30
I ran into your code and looked into it. You've used the Person object array and directly passing it to the oracle.sql.ARRAY constructor. Just curios if this works, cos my understanding is that you need to create a oracle.sql.STRUCT out of ur java object collection and pass it to the ARRAY constructor. I tried ur way but got this runtime exception.
java.sql.SQLException: Fail to convert to internal representation: JavaBulkInsertNew$Option@10bbf9e
                    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
                    at oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:146)
                    at oracle.jdbc.oracore.OracleTypeADT.toDatum(OracleTypeADT.java:239)
                    at oracle.jdbc.oracore.OracleTypeADT.toDatumArray(OracleTypeADT.java:274)
                    at oracle.jdbc.oracore.OracleTypeUPT.toDatumArray(OracleTypeUPT.java:115)
                    at oracle.sql.ArrayDescriptor.toOracleArray(ArrayDescriptor.java:1314)
                    at oracle.sql.ARRAY.<init>(ARRAY.java:152)
                    at JavaBulkInsertNew.main(JavaBulkInsertNew.java:76)
Here's a code snippet I used :
Object optionVal[] =   {optionArr[0]};   // optionArr[0] is an Option object which has three properties
oracle.sql.ArrayDescriptor empArrayDescriptor = oracle.sql.ArrayDescriptor.createDescriptor("TT_EMP_TEST",conn);
ARRAY empArray = new ARRAY(empArrayDescriptor,conn,optionVal);If you visit my thread, u'll see that I'm using STRUCT and then pass it to the ARRAY constructor, which works well, except for the performance issue.
I'll appreciate if you can provide some information.
Regards,
Shamik

Similar Messages

  • How to pass Array of Java objects to Callable statement

    Hi ,
    I need to know how can I pass an array of objects to PL/SQL stored procedure using callable statement.
    So I am having and array list of some object say xyz which has two attributes string and double type.
    Now I need to pass this to a PL/SQL Procedure as IN parameter.
    Now I have gone through some documentation for the same and found that we can use ArrayDescriptor tp create array (java.sql.ARRAY).
    And we will use a record type from SQL to map this to our array of java objects.
    So my question is how this mapping of java object's two attribute will be done to the TYPE in SQL? can we also pass this array as a package Table?
    Please help
    Thanks

    I seem to remember that that is in one of Oracle's online sample programs.
    http://www.oracle.com/technology/sample_code/tech/java/sqlj_jdbc/index.html

  • What is the best book of objective c and from where i can download it?

    what is the best book of objective c and from where i can download it?

    Before purchasing a book be sure to exhaust the excellent resources on the Apple Developer Site. There are quite a few guides, references, and samples for Objective-C.
    Learning Objective-C: A Primer
    The Objective-C Programming Language
    Object-Oriented Programming with Objective-C
    etc.
    If you are developing for Mac or iOS, there are plenty of other documents describing the frameworks, including the Cocoa Fundamentals Guide,  iOS App Programming Guide, etc.
    If you want to create iOS apps, start here.
    Start Developing iOS Apps Today

  • How to store and retrieve blob data type in/from oracle database using JSP

    how to store and retrieve blob data type in/from oracle database using JSP and not using servlet
    thanks

    JSP? Why?
    start here: [http://java.sun.com/developer/onlineTraining/JSPIntro/contents.html]

  • Calling java function load and stored in database

    Hi ,
    I try to call a java fonction loaded and published in database (Oracle 8.1.7.4ee). this function call an OS command ... the PL/SQL call is completed but de command set in parameters function is not execute ... next is the code :
    import java.lang.*;
    import java.io.*;
    public class JShell {
    public static void execute (String command) throws IOException {
    try {
    Process child = Runtime.getRuntime().exec(command);
    } catch (IOException e) {
    calling this function with java main is OK
    import java.lang.*;
    import java.io.*;
    public class TestJShell {
    static public void main(String args[]) throws Exception
    JShell.execute(args[0].toString());
    java TestJShell 'cp /test/myfile.txt /test/myfile.sav'
    copy is donethen when the fuction is loaded and published in database
    as
    loadjava -user ../.. JShell.class
    CREATE OR REPLACE PROCEDURE JShell_exe (Commande in VARCHAR2) AS LANGUAGE JAVA NAME 'JShell.execute(java.lang.String)';run is
    CALL ell_exe ('cp /test/myfile.txt /test/myfile.sav');
    call is completed but no copy is doneCan somebody help me ? thanking you in anticipation;

    Firs things first:
    1)Which copy of your class is loaded in the DB ( it seems that you have two different classes JShell and TestJShell ).
    2)Do you have permisions for file manipulation ?
    3)Do you get any errors ?

  • Can you suggest a best way to store and read arabic from oracle database?

    Hi ,
    can you suggest a best way to store and read arabic from oracle database?
    My oracle database is Oracle Database 10g Release 10.1.0.5.0 - 64bit Production on unix HP-UX ia64.
    NLS_NCHAR_CHARACTERSET AL16UTF16
    NLS_LANGUAGE AMERICAN
    NLS_TERRITORY AMERICA
    NLS_CHARACTERSET WE8ISO8859P1
    I have presently stored the data in nvarchar2 field. But i am not able to display it correctly.

    Using the national characterset should work but there are other factors that you have to consider when working with NCHAR/NVARCHAR2/NCLOB.
    If possible, changing the characterset is usually the best solution if it's a possiblity for you.
    For more info:
    Dear Gurus: Can u pls explain the difference between VARCHAR2 & NVARCHAR2??

  • I export dump from oracle database 8.1.7 and try to import in 10.2.0. while import its prompt error

    I export dump from oracle database 8.1.7 and try to import in 10.2.0. while import its prompt error as follow
    8.1.7
    SQL> select * from nls_database_parameters where parameter like '%SET%';
    PARAMETER                      VALUE
    NLS_CHARACTERSET               US7ASCII
    NLS_NCHAR_CHARACTERSET         US7ASCII
    10.2.0
    SQL> select * from nls_database_parameters where parameter like '%SET%';
    PARAMETER                      VALUE
    NLS_NCHAR_CHARACTERSET         AL16UTF16
    NLS_CHARACTERSET               WE8MSWIN1252
    C:\Documents and Settings\Administrator>imp system/manager file=H:\CGlByte\cglby
    te_03-07-2013Wed.dmp fromuser=system touser=cglbyte ignore=y
    Import: Release 10.2.0.4.0 - Production on Thu Jul 4 16:11:49 2013
    Copyright (c) 1982, 2007, Oracle.  All rights reserved.
    Connected to: Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - Produc
    tion
    With the Partitioning, OLAP, Data Mining and Real Application Testing options
    Export file created by EXPORT:V08.01.07 via conventional path
    import done in US7ASCII character set and AL16UTF16 NCHAR character set
    import server uses WE8MSWIN1252 character set (possible charset conversion)
    export client uses WE8ISO8859P1 character set (possible charset conversion)
    export server uses US7ASCII NCHAR character set (possible ncharset conversion)
    Import terminated successfully without warnings.
    Pl suggest remedy
    Regards,

    8.1.7
    AMERICAN_AMERICA.WE8ISO8859P1
    10.2.0
    AMERICAN_AMERICA.WE8MSWIN1252
    exp system/manager file=d:\cgl.dmp owner=cgl, even i set character set before export but no impact

  • Send and recieve sms from oracle(database+application server)

    HI all
    I Wanted to send and recieve SMS not mails from oracle(database/application server).any possible solutions and what are the things that i required for that.i-e any service provider or any machine or somethings else.

    Handle: taimur
    Status Level: Newbie
    Registered: Aug 3, 2009
    Total Posts: 42
    Total Questions: 16 (16 unresolved)
    so many questions without ANY answers.
    http://forums.oracle.com/forums/ann.jspa?annID=718
    http://www.lmgtfy.com/?q=oracle+send+sms
    Edited by: sb92075 on Nov 20, 2010 7:23 PM

  • How to call MSSQL stored procedure from oracle database

    MSSQL and Oracle databases are linked thru ODBC link using Oracle HSODBC.
    I can query MSSQL table or view from Oracle Database using standard notation for acessing remote objects schema.object@dblink_name...
    Can anybody give me syntax for calling MSSQL stored procedure thru ODBC database link?
    I tried syntax exec schema.stored_procedure@dblink_name but it doesn't work...i'm getting schema.stored_procedure must be declared error...
    Tnx,in advance!
    Dejan Botica

    Oracle database 10gR2.
    MSSQL2000 database.
    For example query:
    select * from dbo.Tbl_Test@kron@dw_jamnica; works fine...
    ...while for example exec dbo.Test@kron@dw_jamnica;
    reports error:
    ORA-06550: line 1, column 7:
    PLS-00201: identifier 'DBO.TEST@KRON@DW_JAMNICA' must be declared
    ORA-06550: line 1, column 7:
    PL/SQL: Statement ignored
    Table Tbl_Test and procedure Test exists in MSSQL instance.
    Regards,
    Dejan

  • Walkthrough: Displaying Data from Oracle database in a Windows application.

    This article is intended to illustrate one of the most common business scenarios such as displaying data from Oracle database on a form in a Windows application using DataSet objects and .NET Framework Data Provider for Oracle.
    You can read more at http://www.c-sharpcorner.com/UploadFile/john_charles/WalkthroughDisplayingDataOracleWindowsapplication05242007142059PM/WalkthroughDisplayingDataOracleWindowsapplication.aspx
    Enjoy my article.

    hi,
    this is the code :
    public class TableBean {
    Connection con ;
    Statement ps;
    ResultSet rs;
    private List perInfoAll = new ArrayList();
    public List getperInfoAll() {
    int i = 0;
    try
    con = DriverManager.getConnection("url","root","root");
    ps = con.createStatement();
    rs = ps.executeQuery("select * from user");
    while(rs.next()){
    System.out.println(rs.getString(1));
    perInfoAll.add(i,new perInfo(rs.getString(1),rs.getString(2),rs.getString(3)));
    i++;
    catch (Exception e)
    System.out.println("Error Data : " + e.getMessage());
    return perInfoAll;
    public class perInfo {
    String uname;
    String firstName;
    String lastName;
    public perInfo(String firstName,String lastName,String uname) {
    this.uname = uname;
    this.firstName = firstName;
    this.lastName = lastName;
    public String getUname() {
    return uname;
    public String getFirstName() {
    return firstName;
    public String getLastName() {
    return lastName;
    ADF table code:
    <af:table value="#{tableBean.perInfoAll}" var="row"
    binding="#{backing_Display.table1}" id="table1">
    <af:column sortable="false" headerText=""
    align="start">
    <af:outputText value="#{row.firstName"/>//---> Jdeveloper 11g doesn't allow me to use this.. it says firstName is an unknown property..
    </af:column>
    </af:table>
    Please tell me is this the way to do it.. or is it a must to use the DataCollection from the data controls panel...
    Thanks...

  • Calling Dot Net program From oracle Database

    Hi
    is there any way to call DOT NET program Like C# from oracle database, i mean is there way to call it from pl-sql stored procedure or trigger ..etc
    I read that is possible with java , C, C++, but is it possible with C#
    Best Regards

    If your Oracle database is running on Windows and is a reasonably recent version (I believe 10.1 or later), it has the ability to create .Net stored procedures just like you have the ability to create Java stored procedures. That tends not to be a particularly commonly used feature but it's an option. If you compile your .Net application to a DLL, you could also call it as an external procedure.
    More commonly, however, if you're talking about a .Net program that is deployed on a middle tier server, however, would be for the .Net application to expose an API (say, a web service API) that the database could invoke (via UTL_DBWS or UTL_HTTP).
    Justin

  • Performance Issue: Retrieving records from Oracle Database

    While retrieving data from Oracle database we are facing performance issues.
    The query is returning 890 records and while displaying it on the jsp page, the page is taking almost 18 minutes for displaying records.
    I have observed that cpu usage is 100% while processing the request.
    Could any one advise what are the methods at DB end or Java end we can think of to avoid such issues.
    Thanks
    R.

    passion_for_java wrote:
    Will it make any difference if I select columns instead of ls.*
    possibly, especially if there's a lot or data being returned.
    Less data over the wire means a faster response,
    You may also want to look at your database, is that outer join really needed? Does it perform? Are your indexes good?
    A bad index (or a missing one) can kill query performance (we've seen performance of queries drop from seconds to hours when indexes got corrupted).
    A missing index can cause full table scans, which of course kill performance if the table is large.

  • How to call web services from oracle database 10g

    Hi all ,
    How can i call web services from oracle database 10g ?
    thanks ...

    abdou123 wrote:
    but how can i get complex result
    for example
    i pass input parameter like National Id Number
    and get the person details ( name , age , date of birth , ............ ) .Basic approach to web services using UTL_HTTP explained in {message:id=10448611}.
    An example of using a pipeline table function as a data transformation process (turning web data into rows and columns) in {message:id=10158148}.

  • Send mail from oracle database 10g

    Hi ,
    I need to send a test mail from oracle database 10g to my gmail account through a stored procedure .
    I will pass the list of recipents , subject and text of the mail through parameters .
    Can anyone give me the code of the storerd procedure please ,
    Thank you .

    hi, for example
    DECLARE
    mail_conn UTL_SMTP.connection;
    smtp_relay VARCHAR2(32) := '172.16.x.x';
    recipient_address VARCHAR2(64) := '[email protected]';
    sender_address VARCHAR2(64) := '[email protected]';
    mail_port NUMBER := 25;
    msg VARCHAR2(200);
    BEGIN
    mail_conn := UTL_SMTP.open_connection(smtp_relay,mail_port);
    UTL_SMTP.HELO(mail_conn, smtp_relay);
    UTL_SMTP.MAIL(mail_conn, sender_address);
    UTL_SMTP.RCPT(mail_conn, recipient_address);
    UTL_SMTP.DATA(mail_conn, 'Payment request iniated');
    UTL_SMTP.QUIT(mail_conn);
    end;

  • DBA Cockpit: Planning calendar and remote Oracle databases- which method?

    For using DBA Planning Calendar to schedule BR*Tools for remote Oracle database AS Java systems I have successfully implemented both the Secure Shell and SAP gateway methods in [Note 1025707 - DBA Cockpit: Planning calendar and remote Oracle databases|https://service.sap.com/sap/support/notes/1025707] and was interested in which of these two methods others have found to be more supportable and maintainable?
    In more detail, the note has these two methods for non-ABAP remote systems:
    2. Connection through Remote/Secure Shell
    Specifically Secure Shell. Rejecting remote shell as too old and insecure a protocol.
    3 Connection through SAP gateway
    The note provides clues as to how these methods work. Expanding on that:
    With #2, central ABAP system calls out to its OS user level to execute the ssh client (after gw/rem_start has been set to the non-default value SSH_SHELL) which it finds in the location specified in gw/ssh (default value is /usr/bin/ssh). It must use password-less authentication and the key-based authentication must also not require a passphrase. (Using ssh-agent is not an option since this is being called from SAP, not from your own script.)
    It remotely runs via ssh a command, sapxpg, which must be found in the PATH of the remote user. (This is why the note, which has you place this exe sapxpg and a subset of the BR*Tools in the home dir of the remote user, also has you make sure the home dir is included in the path--your OS might or might not include the user's home dir in the path in the default shell environment for a new user.)
    Then via sapxpg, the BR*Tools are invoked.
    One thing that may be confusing here is you have to check at least one gateway parameter 'gw/...' in the central system to get the method #2 the non-gateway method to work--this is because the two methods are technically almost the same: in #2, secure shell is used to basically start a gateway on the fly with sapxpg in order to call the BR*Tools each time a DBA Planning Calendar action runs or you view DBA or Backup logs of the remote system from the central system. With #3, the gateway runs continuously on the remote system.
    With #3, central system connects to remote SAP standalone gateway, which executes the BR*Tools installed in the standard SAP kernel directory of the SAP gateway. This method is simpler to describe so it sounds like it has less components than the secure shell method, however you do have an entire SAP system running, although it is just a standalone gateway.
    Thoughts:
    These pros/cons are UNIX/Linux-oriented since I assume most Windows environments do not have added 3rd-party products that provide secure shell so SAP gateway is the only method.
    Secure shell
    + Less software required (not counting secure shell which comes with the operating system distribution): just a few SAP executables placed in the home dir of an ordinary user on the remote system.
    + Secure shell service probably automatically starts upon boot of the remote system operating system.
    + Secure shell is a widely used tool outside of SAP for executing commands remotely without passwords.
    - Installation is non-standard: shell environment of remote user is not adapted by SAP installer since SAP installer is not used, SAP executables in the home dir of the remote user is non-standard. Has to be setup manually.
    - Requires setting up secure shell key-based authentication, which should be known by UNIX/Linux admins or combined Basis/UNIX/Linux admins, but might be less familiar to SAP Web AS only admins.
    - If your admin config policy is to have SAP interact as little possible with the OS level for interfaces with other systems, here you are relying on the OS-level secure shell.
    - Using a private key that does not require a passphrase on the central system may not fit with your security policies if you have standards for secure shell configuration.
    SAP gateway
    + The gateway is a standard installation, performed with SAP installation tool, with the exception of a few additional environment settings that have to be added after the installation. BR*Tools are installed in the standard location. Can use standard procedures for updating this software.
    + Only uses SAP software.
    - More software on remote system: standalone gateway just to run BR*Tools and view logs.
    - SAP Kernel of remote gateway should probably be updated whenever you do SAP kernel updates across your systems for consistency. One more system to update.
    - Shell environment of remote user that runs the gateway looks like something setup by the SAP installer but is not standard because it has a few additional environment variables added.
    - Need to make sure the SAP gateway is started on the remote system.

    Hi Joe,
    I configured a monitoring/dba landscape for two SAP Portals and one SAP BusinessObjects system on a SAP landscape by using DBACOCKPIT, at a customer site. These systems are running on AIX, Windows 2003/2008 servers and attached to the central monitoring system with standalone SAP gateway installations.
    One another reason to not use OS based commands or 3rd party tools is security. We are stopping and disabling most of the services on OS where SAP system is running on, because of the security reasons. I faced more security gaps on rsh/ssh and the other tools than standalone SAP Gateway installations. As you can figure out that rsh/ssh is getting more attack than standalone SAP Gateway, because of well known by the IT world.
    As a summary of it, this depends to point of view and policy of the IT organization. I applied both ssh and standalone SAP Gateway solutions at my customers, but I choose standalone SAP Gateway installation among of them.
    Best regards,
    Orkun Gedik

Maybe you are looking for

  • Schedule archiving jobs

    Hi, We are trying to schedule periodically the archiving jobs for several objects. To be more specific, we begin with MM_EKKO archiving object and we would like to chain the 3 steps : preprocessor the write, then delete. Chaining delete after write i

  • SETTING DEFAULT LANGUAGE IN BEA WEBLOGIC SERVER 11G

    Hello, I want to change the default language for Oracle Bea Web Logic 11G (10.3.4.0). Can anyone tell me in what opcion can i do it? Thanks in advance. Regards,

  • Would you get a macbook air today?

    I heard rumours that there would be new macbook airs on or around March. I am 80% sure about this because intel will release its Ivy core on March which apple planned to use for the new macbook air and pro. I actually planned to get it on Christmas b

  • Windows did not detect any networking hardware iMac 27' 2013 model

    Installed windows 7 using bootcamp now when I go to connect to a network it says windows did not detect any networking hardware

  • Security Apps

    Anyone know if there is an app out there that would block syncing with iTunes without a password, or restrict deletion of texts without a password?