How do I Serialize Object to Database for Hibernate to read in Java

穿精又带淫゛_ 提交于 2020-01-02 05:31:54

问题


I'm currently writing a tool to plug into an existing enterprise application that uses Hibernate. My tool at install time needs to write some values into the database where one of the columns is a serialized version of a setting descriptor object. This object has two lists of objects and a few primitive types.

My current approach is to create a ByteArrayOutputStream and an ObjectOutputStream and then write the ObjectOutputStream to the ByteArrayOutputStream, then passing the resulting byte array into the sql with Spring's 1SimpleJdbcTemplate1. My current issue with this approach is that when the enterprise tool pulls my rows it fails to de-serialze the column with the following:

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

I feel I may need to serialize the inner objects, but have no clue how to do that and keep everything together.


回答1:


Ended up solving my own problem. In the hibernate API there is a class called SerializationHelper that has a static function serialize(Serializable obj) which I was able to use to serialize my object and then insert it into the database. Hibernate was then able to read it in the enterprise app.




回答2:


You can serealize a Java object into bytes and then store it in a BLOB.

Serialize:

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;
    }


来源:https://stackoverflow.com/questions/5966039/how-do-i-serialize-object-to-database-for-hibernate-to-read-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!