Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing Serializable Objects in the Database

I'm writing an application which needs to write an object into database.

For simplicity, I want to serialize the object.

But ObjectOuputStream needed for the same purpose has only one constructor which takes any subclass of OutputStream as parameter.

What parameter should be passed to it?

like image 334
Mahesh Gupta Avatar asked Feb 22 '11 15:02

Mahesh Gupta


People also ask

Can you store objects in a database?

You can store objects in relational tables as column objects or in object tables as row objects. Those objects that have meaning outside of the relational database they reside in, should be made referenceable as row objects in an object table. Otherwise, they should be stored as column objects in a relational table.

How does mysql store serialized data?

The workaround: use MEDIUMBLOB or just BLOB , as long as those types are sufficient to store your serialized data. Associate serialized data with other more relational data. Ability to store and fetch serialized data according to transaction scope, COMMIT, ROLLBACK.

Can we store Java object in database?

Some database products enable you to directly store Java objects as column data in a database. In such databases, Java classes are treated as datatypes, and you can declare a column with a Java class as its datatype.


1 Answers

You can pass a ByteArrayOutputStream and then store the resulting stream.toByteArray() in the database as blob.

Make sure you specify a serialVersionUID for the class, because otherwise you'll have hard time when you add/remove a field.

Also consider the xml version for object serialization - XMLEncoder, if you need a bit more human-readable data.

And ultimately, you may want to translate your object model to the relational model via an ORM framework. JPA (Hibernate/EclipseLink/OpenJPA) provide object-relational mapping so that you work with objects, but their fields and relations are persisted in a RDBMS.

like image 120
Bozho Avatar answered Oct 20 '22 14:10

Bozho