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<T>
) 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:
- With the session open, touched the entire object graph to force-load any unloaded entities;
- Closed the Hibernate session (including any transactions involving its connection);
- 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: @brd6644 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).