How to serialize an object in a sleep database for reading in Java

I am currently writing a tool to connect to an existing enterprise application using Hibernate. My tool during installation should write some values ​​to the database, where one of the columns is a serialized version of the installation descriptor object. This object has two lists of objects and several primitive types.

My current approach is to create ByteArrayOutputStreamand ObjectOutputStreamthen write ObjectOutputStreamto ByteArrayOutputStreamand then pass the resulting byte array to sql using Spring 1SimpleJdbcTemplate1. My current problem with this approach is that when an enterprise tool pulls my rows, it cannot deceive a column like this:

org.springframework.orm.hibernate3.HibernateSystemException: could not deserialize; nested exception is org.hibernate.type.SerializationException: could not deserialize

I feel that I may need to serialize internal objects, but I don’t know how to do this and keep everything together.

+3
source share
2 answers

The solution to my own problem has ended. The hibernate API has a class called SerializationHelper , which has a static function serialize(Serializable obj)that I could use to serialize my object and then paste it into the database. Then Hibernate was able to read it in a corporate application.

+4
source

You can drill a Java object into bytes and then save it in a BLOB.

Serialization:

ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream objOut = new ObjectOutputStream(byteOut);
objOut.writeObject(object);
objOut.close();
byteOut.close();
byte[] bytes = byteOut.toByteArray()

Deserialize:

 public <T extends Serializable> T getObject(Class<T> type) throws IOException, ClassNotFoundException{
        if(bytes == null){
            return null;
        }
        ByteArrayInputStream byteIn = new ByteArrayInputStream(bytes);
        ObjectInputStream in = new ObjectInputStream(byteIn);
        T obj = (T) in.readObject();
        in.close();
        return obj;
    }
+1
source

All Articles