简体   繁体   中英

InvalidClassException while deserializing blob field from database

When I was trying to retrieve blob data from the database(mysql), I got the below exception.

java.io.InvalidClassException: 
com.nmsworks.cygnet.tmf.mtnm.elements.SNCUserData; local class 
incompatible: stream classdesc serialVersionUID = -7634696886161105104, 
local class serialVersionUID = -7522169448179471613

I believe some changes had taken place in the SNCUserData class after the data was stored in the database. I didn't declare a default serial version UID in the class. I can see that's what causing the problem. If I had declared UID, I would not have received this Exception. My question is instead of storing the object as blob in the database, is there any other way to save the object so that I don't have to serialize and deserialize the object whenever I store and retrieve it from the database? I don't want to declare a serial version UID in the class since it is a heavy structure that, in turn, has a lot of serializable objects, for which I have to declare UID, inside it.

I believe some changes had taken place in the SNCUserData class after the data was stored in the database. I didn't declare a default serial version UID in the class. I can see that's what causing the problem.

That would be sufficient to cause the problem.

If I had declared UID, I would not have received this Exception.

That is correct. But you may have gotten different exceptions; eg if you had added, removed, reordered or changed the types of any of the fields.

My question is instead of storing the object as blob in the database, is there any other way to save the object so that I don't have to serialize and deserialize the object whenever I store and retrieve it from the database?

The alternative is to create a new table or tables with columns to represent the fields of the object. Then write some Java code to map between objects and table rows.

I don't want to declare a serial version UID in the class since it is a heavy structure that, in turn, has a lot of serializable objects, for which I have to declare UID, inside it.

Well yea. But that's the least of your worries. If you do start declaring serial UIDs then if you change the structure of the classes then you probably need to write custom readObject and writeObject methods to deal with this.

For what it is worth, putting serialized objects into databases is generally a bad idea. The "modern" way to persist complex objects is to use an object-relational mapping such as JPA (eg Hibernate) or JDO. But even then, you can get into problems if you make radical changes to the classes you are persisting.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM