how to write and read object into database

Iam using serializable to write/read object from/to database, but I switched my jdk to new version and Iam getting exceptions while reading the serialized object from my databse which is serialized by old jdk api. I want to know what is the problem, can I solve this problem by externalizable instead of serializable.
kyama1Asked:
Who is Participating?
 
Mig-OConnect With a Mentor Commented:
You cannot deserialize objects, that have changed over java versions. The reason is, that fields may have been changed within the objects.

Sad to say, but there is no solution to your problem. Read the Java Documentation (the part of Serialisation), and you see, that thare is a serialId generated from the structure of the class. In new jdk, if class changes, the serialId changes, and you cannot read in old objects.

If you want to persist objects over more than one version, you have to write your own representation objects, and store them (This is one way), or store the stuff in an XML Stream (you will for sure be able to read this thing in 150 years) :)
0
 
Mig-OCommented:
oh, one solution might be, to just add a static long named "serialId=<somebignumberofyourchoice>" to your class before serializing it. Then it deserializes with new jdks fine, AFAIK!
0
 
aozarovConnect With a Mentor Commented:
Just replacing the JDK (without changing your code) and getting this exception means that your serialized objects were holding
some JDK objects which changed their signature and didn't not have a serialVersionUID value. That is surprising because Java
API code tend to have a serialVersionUID in its Serializable classes. Can you tell which class the exception points to?
If you also changed your code (and this is the cause of the problem) then you can solve it in two ways.
1. as Mig-O suggested add to your current class a serialVersionUID value (see http://java.sun.com/j2se/1.4.2/docs/tooldocs/solaris/serialver.html 
for how to generate the value) which *was generated for your old version of the class*.
2. implement "private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException" in your offending Serializable
class or its Container and inside use the readFields method (http://java.sun.com/j2se/1.4.2/docs/api/java/io/ObjectInputStream.html#readFields() ) to read and populate the fields that you are interested in. (don't call super.defaultReadObject())

0
 
aozarovCommented:
BTW, option 2 should be used together with option 1 if you are applying the change to the offending class itself and not to its parent class.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.