Sergio.
You should use BLOB. It is pretty straighforward with JDBC.
The problem with the second code you posted it's the encoding you should additionally encode the bytes to make sure none of them fails.
If you still want to write it down into a String you can also encode the bytes using Base64.
Java does not have a "public" implementation for that ( though sun.misc, and java.util.prefs have implementations and the source is available, but check the license for those )
Or you can use the following simple Base64Coder open source impl.
http://www.source-code.biz/snippets/java/2.htm
Still you should use CLOB as data type, because you don't know how long the serialized data is going to be.
Here is a sample of how to use it.
import java.util.*;
import java.io.*;
/**
* Usage sample serializing SomeClass instance
*/
public class ToStringSample {
public static void main( String [] args ) throws IOException,
ClassNotFoundException {
String string = toString( new SomeClass() );
System.out.println(" Encoded serialized version " );
System.out.println( string );
SomeClass some = ( SomeClass ) fromString( string );
System.out.println( "\n\nRestituted object");
System.out.println( some );
}
/** Read the object from Base64 string. */
private static Object fromString( String s ) throws IOException ,
ClassNotFoundException {
byte [] data = Base64Coder.decode( s );
ObjectInputStream ois = new ObjectInputStream(
new ByteArrayInputStream( data ) );
Object o = ois.readObject();
ois.close();
return o;
}
/** Write the object to a Base64 string. */
private static String toString( Serializable o ) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream( baos );
oos.writeObject( o );
oos.close();
return new String( Base64Coder.encode( baos.toByteArray() ) );
}
}
/** Test subject. A verey simple class */
class SomeClass implements Serializable{
int i = Integer.MAX_VALUE;
String s = "ABCDEFGHIJKLMNOP";
Double d = new Double( -1.0 );
public String toString(){
return "SomClass instance says: Don't worry, " +
"I'm healty look, my data is i = "+ i + ", s = "+ s + ", d = "+ d;
}
}
Output:
C:\oreyes\samples\java\encode>javac *.java
C:\oreyes\samples\java\encode>java ToStringSample
Encoded serialized version
rO0ABXNyAAlTb21lQ2xhc3PSHbLk6OgfswIAA0kAAWlMAAFkdAASTG
phdmEvbGFuZy9Eb3VibGU7TAABc3QAEkxqYXZhL2xhbmcvU3RyaW5nO3
hwf////3NyABBqYXZhLmxhbmcuRG91YmxlgLPCSi
lr+wQCAAFEAAV2YWx1ZXhyABBqYXZhLmxhbmcuTnVtYmVyhqyVHQ
uU4IsCAAB4cL/wAAAAAAAAdAAQQUJDREVGR0hJSktMTU5PUA==
Restituted object
SomClass instance says: Don't worry, I'm healty look,
my data is i = 2147483647, s = ABCDEFGHIJKLMNOP, d = -1.0