Issue with serializing Hibernate objects using XStream

前端 未结 6 1511
南笙
南笙 2021-02-04 19:52

I\'ve been facing this issue where, the hibernate objects on serialization produces unexpect xmls containing all the instrumented code from Hibernate.

We did some cleani

6条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-04 20:33

    I've not used XStream before, but I have serialized Hibernate-managed entities. It isn't fun.

    There are two big issues:

    • Lazy loading;
    • One-to-many relationships.

    The former is obvious - you need the actual data to serialize. The latter is less so - any one-to-many relationships you declare against collection interfaces (eg: Set) will get plugged by Hibernate's own (unserializable!) collection implementations. This may well be where Hibernate's classes are bleeding into your objects.

    I ended up writing reflective code (actually introspective) that did this:

    1. With the session open, touched the entire object graph to force-load any unloaded entities;
    2. Closed the Hibernate session (including any transactions involving its connection);
    3. Walked the object graph, replacing any lists, sets or maps with instances of ArrayList, HashSet or HashMap (known-serializable collections).

    Note that step 2 is important - if you replace the collections prior to closing the session, Hibernate will just put its own collections right back upon close...

    Edit: @cliff.meyers spotted a detail of the implementation I forgot to mention: if you do this, you need to limit object graph walking only to your own entities, and watch for circular reference paths (eg: by caching references to objects you've already walked).

提交回复
热议问题