简体   繁体   中英

Can Hibernate JPA objects be reliably serialized using default Java serialization?

Imagine I have a typical multi-table RDBMS schema and a complex entity hierarchy using all (or many) of the various Hibernate relationships. There will be collections classes as some of the fields (Sets, Lists) to manage the relationships in Java, and circular references. There could be lazy loading, so behind the scenes there will be proxy classes.

Then I decide I want to serialize this object hierarchy using default Java serialization and perhaps deserialize it later back into memory (assume back to the same system). Is this straightforward, or are there pitfalls and circumstances where it won't work? Could there be issues if some of the related objects have not yet lazy-loaded, for example?

We instance entity objects in an ORM in order to match the current information in the database, and these objects tend to rely heavily (as you suggest) on a live (or resurrectable :P) connection to the database in order to recover its information, one piece each time.

In order to avoid these problems, I would suggest you to eagerly fetch the full information of each entity before trying to serialize the information. The serialization mechanism falls to you, but you should consider lots of things if trying to use Java native mechanism ( https://javajee.com/best-practices-for-serialization-in-java ) instead of a lighter one, and more independent from the implementation.

Anyway, and this is just a personal opinion, I think you are not using properly the information given by an ORM suggesting to serialize the entity objects, since it creates an arbitrary snapshot of the database status in an arbitrary moment, and this can be totally inaccurate in a future moment when you want to recover these objects into memory.

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