Rollerball
Rollerball

Reputation: 13108

Difference between Serialization and saving an object via JDBC to JAVA_OBJECT

I am aware of what Serialization is however I have not found any real practical example describing the latter one (saving an object in a database taking advantage of the JAVA_OBJECT mapping). Do I have first to serialize the object and then save it to the database?

Upvotes: 1

Views: 3158

Answers (2)

Joni
Joni

Reputation: 111259

In the case of MySQL, you don't have to serialize the object first, the driver will do it for you. Just use the PreparedStatement.setObject method.

For example, first in MySQL create the table:

create table blobs (b blob);

Then in a Java program create a prepared statement, set the parameters, and execute:

    PreparedStatement preps;
    preps = connection.prepareStatement("insert into blobs (b) values (?)");
    preps.setObject(1, new CustomObject());
    preps.execute();

Don't forget that the class of the object that you want to store has to implement the Serializable interface.

Upvotes: 3

Juned Ahsan
Juned Ahsan

Reputation: 68715

Serialization is used to save the state of an object and marshall it to a stream and share it with a remote process. The other process just need to have the same class version to deserialize the stream back to an object.

The problem with the database approach is that you will need to expose the databse even to the remote process. This is generally not done due to various reasons, mainly security.

Upvotes: 1

Related Questions