Solved

How to Store Java Class Object in Oracle

Posted on 2004-04-28
29
853 Views
Last Modified: 2013-12-22
Hi,
  I want to store Java Class object in Oracle database,
I have a Serialized class called ProcessDataBean which will contain some values in form of Vectors and i want to create object of it and store in Oracle and retrieve it on some specific time and access stored values.
  How do i do it i need some code examples.
0
Comment
Question by:satish_kore
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 12
  • 9
  • 4
  • +2
29 Comments
 
LVL 86

Expert Comment

by:CEHJ
ID: 10938442
Use a Blob field, and write to the field with an ObjectOutputStream
0
 
LVL 37

Expert Comment

by:zzynx
ID: 10938608
Snippets that can help you (XML serialization):

Loading:

InputStream in = null;
Blob blob = resultSet.getBlob(1);
in = blob.getBinaryStream();
XMLDecoder serializer = new XMLDecoder(in);
yourVariable = (ProcessDataBean) serializer.readObject();
serializer.close();

Binding:

ByteArrayOutputStream out = new ByteArrayOutputStream();
XMLEncoder e = new XMLSerializer(new BufferedOutputStream(out));
e.writeObject(yourVariable);
e.close();  
byte[] byteArray = out.toByteArray();
preparedStatement.setAsciiStream(offset++,
    new ByteArrayInputStream(byteArray), byteArray.length);
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 10938662
You shouldn't need the xml stuff - just ObjectOutputStream.write/ObjectInputStream.read into/from, the blob
0
Optimize your web performance

What's in the eBook?
- Full list of reasons for poor performance
- Ultimate measures to speed things up
- Primary web monitoring types
- KPIs you should be monitoring in order to increase your ROI

 
LVL 23

Expert Comment

by:rama_krishna580
ID: 10939630
try this..

$ loadjava -u scott/tiger -v -resolve EmpManager.java

http://www.developer.com/db/article.php/3337411

R.K
0
 
LVL 23

Expert Comment

by:rama_krishna580
ID: 10939647
Loading the Java Class into the Database
Once the Java class is created, the next step is to  use the Oracle loadjava tool to load the Java class into the database. You can also invoke the loadjava tool by calling the dbms_java.loadjava ('...') procedure from SQL*Plus. The following command shows the loadjava tool loading the Person class into the database:

% loadjava -u SCOTT/TIGER -r -f -v Person.class

........................

http://otn.oracle.com/products/oracle9i/daily/may28.html

R.K
0
 
LVL 1

Author Comment

by:satish_kore
ID: 10946211
Hi zzynx and all,
   First up all i would like to thank all the people.
  zzynx, i have implemented ur code but i m getting error like "java.sql.SQLException: ORA-01465: invalid hex number".
  What could be the problem?
My code as follows:

ProcessDataBean myBean = new ProcessDataBean();
myBean.setMybyte(new byte[]{00,11}); //class will contain vector of byte array

public void insertvalues(String query)
{
   try
   {
       PreparedStatement pstmt = connection.prepareStatement(query);
      //Binding object
      ByteArrayOutputStream out = new ByteArrayOutputStream();
      XMLEncoder e = new XMLEncoder(new BufferedOutputStream(out));
      e.writeObject(myBean);
      e.close();  
      byte[] byteArray = out.toByteArray();
      pstmt.setAsciiStream(1,new ByteArrayInputStream(byteArray), byteArray.length);
      pstmt.executeUpdate(); //Error in this line
  }
  catch (SQLException e)
  {
      System.out.println(""+e);
  }
}
0
 
LVL 1

Author Comment

by:satish_kore
ID: 10946518
Hi rama_krishna580,
  Loading class will not solve my problem coz i need to store live object in database which will contain some runtime values in form of vectors which will be loaded at runtime.
  I think if i load class according to your instruction it will be like loading empty class without any values.
correct me if i m wrong.
0
 
LVL 37

Expert Comment

by:zzynx
ID: 10946762
>> What could be the problem?

I guess you try to insert a new record containing that blob.
Then the trick is this:
 - First insert that record with an empty blob [ empty_blob() ] for the blob field.
 - After that select that field and update it with the blob data you wanted to insert
0
 
LVL 1

Author Comment

by:satish_kore
ID: 10947804
>>> After that select that field and update it with the blob data you wanted to insert
  Can u give me code example on how to update blank blob field?
0
 
LVL 1

Author Comment

by:satish_kore
ID: 10956754
is anybody out there listening me ? please help me out its real urgent
0
 
LVL 37

Expert Comment

by:zzynx
ID: 10956951
I hear you.

First you perform a normal update for the other fields but for the Blob field you do:
e.g.
update yourtable set field = 1, searchfilterv = empty_blob() where id=8

then you perform something like:

protected void updateBlob(Connection connection) throws SQLException {
        StringBuffer buffer = new StringBuffer("select searchfilterv from ");
        buffer.append(getTableName());
        buffer.append(" where ");
        buffer.append(whereClause());
        // sql looks like: select searchfilterv from yourtable where id = 8
        PreparedStatement stmnt = connection.prepareStatement(buffer.toString());
        try {
            ResultSet rs = stmnt.executeQuery();
            if (!rs.next()) {
                throw new SQLException("Record not found");
            }            
            try {
                oracle.sql.BLOB blob = (oracle.sql.BLOB) rs.getBlob(1);
                OutputStream out = blob.getBinaryOutputStream();
                XMLEncoder e = new XMLSerializer(new BufferedOutputStream(out));
                e.writeObject(searchFilter);
                e.close();
            } finally {
                rs.close();
            }
        } finally {
            stmnt.close();
        }
    }

success
0
 
LVL 1

Author Comment

by:satish_kore
ID: 10957894
After executing above program i m getting error like


Exception in thread "main" java.lang.AbstractMethodError: oracle.jdbc.driver.OracleResultSetImpl.getBlob(Ljava/lang/String;)Ljava/sql/Blob;
        at DBTest.updateBlob1(DBTest.java:135)
        at DBTest.main(DBTest.java:164)

  And one more thing, in Oracle SQL*Plus prompt i can not able to retrieve table values using select * from myTable command.

  What could be the problem?
0
 
LVL 37

Expert Comment

by:zzynx
ID: 10958647
>> Difficult to say without code

>> in Oracle SQL*Plus prompt i can not able to retrieve table values using select * from myTable command.
1. Does
          select count(*) from myTable
works?

2. Does
          select field1 from myTable
works?
0
 
LVL 1

Author Comment

by:satish_kore
ID: 10959322
Code:

protected void updateBlob1() throws SQLException
{
        StringBuffer buffer = new StringBuffer("select myobj from mytest1 where name='satish'");
        PreparedStatement stmnt = connection.prepareStatement(buffer.toString());
        try
        {
            ResultSet rs = stmnt.executeQuery();
            System.out.println(""+buffer.toString());
            if (!rs.next())
            {
                throw new SQLException("Record not found");
            }            
            try
            {
                oracle.sql.BLOB blob = (oracle.sql.BLOB)rs.getBlob("MYOBJ");    // Error Line
                java.io.OutputStream out = blob.getBinaryOutputStream();
                XMLEncoder e = new XMLEncoder(new BufferedOutputStream(out));
                e.writeObject(myBean);
                e.close();
            }
            finally
            {
                rs.close();
            }
        }
        finally
        {
            stmnt.close();
        }
    }

>> 1. Does select count(*) from myTable works?
yes it works and gives result like :
 COUNT(*)
---------
        1
>> 2. Does select field1 from myTable works?
This dosent work it gives same error:
SP2-0678: Column or attribute type can not be displayed by SQL*Plus
0
 
LVL 1

Author Comment

by:satish_kore
ID: 10959377
The difference between your code and my code is

XMLEncoder e = new XMLSerializer(new BufferedOutputStream(out)); // your code
   XMLSerializer constructor takes 2 parameters one outputstream and other outputformat and XMLEncoder and and XMLSerializer are two different types

XMLEncoder e = new XMLEncoder(new BufferedOutputStream(out)); // is my code
0
 
LVL 37

Expert Comment

by:zzynx
ID: 10960699
>>>> 2. Does select field1 from myTable works?
>>This dosent work it gives same error:
>>SP2-0678: Column or attribute type can not be displayed by SQL*Plus
I hope you changed "field1" by the name of one field of yours and "myTable" by the name of your table?
e.g.
        select myobj from mytest1
So, this fails?
And select count(*) doesn't? That's weird!
0
 
LVL 1

Author Comment

by:satish_kore
ID: 10966789
yes offcourse i have changes "field1" with my field name....
  and i said that "select count(*)" works.

>>>yes it works and gives result like :
>>> COUNT(*)
>>>---------
>>>        1
but still i am facing problem:

Exception in thread "main" java.lang.AbstractMethodError: oracle.jdbc.driver.OracleResultSetImpl.getBlob(Ljava/lang/String;)Ljava/sql/Blob;
        at DBTest.updateBlob1(DBTest.java:135)
        at DBTest.main(DBTest.java:164)

Why is this exception coming ?
for your reference i have given code in my previous comment check it out
0
 
LVL 1

Author Comment

by:satish_kore
ID: 10975065
I have increased points for this question coz this is very important for me to solve this problem ASAP.
  Please help me in that and you are open to suggest me alternate ways also.
My Problem:
   I am trying to build a Fail Over Protection Module, so in that i have to keep track of each and every step taken for some transaction if my application fails to complete transaction by any reason then my master application should be able to recreate the state from the same step where it is failed using stored values from database.
  for that reason i m storing all values in some bean and trying to store that bean object in database so that while recreating state i shd get values as it is (without any loss of information....because all values are in form of byte arrays)

   Thanking you in advance.
0
 
LVL 37

Expert Comment

by:zzynx
ID: 10975846
Online again. :)

In your code

       oracle.sql.BLOB blob = (oracle.sql.BLOB)rs.getBlob("MYOBJ");

should be

       oracle.sql.BLOB blob = (oracle.sql.BLOB)rs.getBlob(1);

getBlob() doesn't accept a String, but a number as parameter.
(number= the order of the selected fields in the statement. You only have one, so...)
0
 
LVL 1

Author Comment

by:satish_kore
ID: 10983739
Hi zzynx,
  Thank for your help and time.
I have solved the problem by converting object into string and storing in table:
CODE:

      public static String getString(Object obj) throws IOException
                {
            String result = null;
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
                  oos.writeObject(obj);
                  oos.close();
                  baos.close();
            result = ISOUtil.hexString(baos.toByteArray());
            return result;
      }
      
      public static Object getObject(String str) throws IOException, ClassNotFoundException
                {
            ByteArrayInputStream bais = new ByteArrayInputStream(ISOUtil.hex2byte(str));
            ObjectInputStream ois = new ObjectInputStream(bais);
            return ois.readObject();
      }      

Function : getString(Object obj) will return u string version of Object
Function : getObject(String str) will return u Object out of string
and then you can easily type cast it and retrieve values.....

   Once again thank you for your time
0
 
LVL 37

Expert Comment

by:zzynx
ID: 10984027
>> Hi zzynx,
>>  Thank for your help and time.
If you feel my (or others') comments have been of some help
please close this question by kindly accept one or more comments.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11677816
>>Accept: zzynx {http:#10975846}

Not necessary to use XML as i mentioned
0
 
LVL 37

Expert Comment

by:zzynx
ID: 11678225
...and in your opinion what does that mean for the recommendation?
0
 
LVL 1

Author Comment

by:satish_kore
ID: 11683083
Hi All,
 To be frank still that problem is not been solved to me.
If anybody gives me working code example where creating class object with some byte array values and store that class object in oracle and then retrieve it and access byte arrays out of that retrieved class object from oracle then i will accept that answer.

Steps:
1) Write one class with some byte array variables
2) Create object of that class by initializing those byte array variables
3) Store that newly created object of class in oracle (use any data type like blob, clob or varchar2)
4) Retrieve that stored object and print those byte array variables
0
 
LVL 37

Expert Comment

by:zzynx
ID: 11683153
>> To be frank still that problem is not been solved to me

1) Then why didn't you say that earlier?
    Why didn't you react on my comment
>> please close this question by kindly accept one or more comments

2) Sorry, you gave me the impression it was solved:
>> I have solved the problem by converting object into string and storing in table
>> Function : getString(Object obj) will return u string version of Object
>> Function : getObject(String str) will return u Object out of string
>> and then you can easily type cast it and retrieve values.....
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 11683489
>>...and in your opinion what does that mean for the recommendation?

Not much now by the looks of things - it looks as though you've got your work cut out if you want the points - you can ditch the xml along the way ;-)
0
 
LVL 1

Author Comment

by:satish_kore
ID: 11684349
Yes my problem is been solved temporarily by doing string conversion of object and vice - versa. but that will work in case you have less than 4000 character object (string version of obj)
  But none of answers are helped me to get out of object storage problem so i am still expecting some solution for it.
  And this is not question of ditching anybody this is just it didn’t helped me.
If you want then i can still accept the answers and split points between you guys....but then what about my problem ?
  I would like somebody to solve this issue ASAP.
0
 

Accepted Solution

by:
modulo earned 0 total points
ID: 11703244
PAQed, with points refunded (400)

OK, problem not solved, but there's valuable info here so I'll PAQ/refund this question.
Thus allowing satish_kore to repost the question with the additional length information.

modulo
CS Moderator
0

Featured Post

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Introduction Raise your hands if you were as upset with FireMonkey as I was when I discovered that there was no TListview.  I use TListView in almost all of my applications I've written, and I was not going to compromise by resorting to TStringGrid…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.
Suggested Courses

628 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question