I want to understand when/how hibernate serializes and/or deserializes composite key objects. I have concern in this area for a composite key which includes a @ManyToOne entity association. Consider this example where I have included just enough code to illustrate the scenario:
@Entity public class Foo { @Id private int id;
<lots more persistent fields including entity associations> }
@Entity public class Bar { @Id @Embedded private CompositeId id; }
@Embeddable public class CompositeId implements Serializable { @ManyToOne private Foo;
private int subId; }
My concern would be that the default serialization of CompositeId would only use the subId field, since Foo does not implement Serializable. I could fix this by having Foo implement Serializable, but then the entire Foo object would be serialized and all I really want is the @Id field Foo.id. I could provide a Foo.writeObject() method used during java serialization and constrain so that only the Foo.id field is written on serialization, but then what would I provide as a Foo.readObject() method for deserialization? I cannot create a full Foo object just from Foo.id, without using the EntityManager to load the entity from the database via the id.
I am stuck on this, looking for insight from others. I'm wondering when/how hibernate internally serializes and deserializes the composite @Id object anyway. I can imagine that they serialize the key object of any Foo instance, to provide a key for the Foo instance when it is loaded into the session. But would hibernate every then try to deserialize that key back into the actual composite key object? Maybe it is good enough to provide writeObject() for serialization without having a valid readObject for deserialization.
This is not a new issue. I have seen many old conversations in this general area. Just never seen a full explanation of what is really going on. Can anyone provide that explanation and/or a good suggestion on how to code through this issue?
One thought I have is to code a @Transient fooId field into the CompositeId class. Set fooId from foo, and then serialize/deserialize using the transient fooId and not foo. This means the foo association would be null in the deserialized object, but that probably would not matter for any way that hibernate would be using the CompositeId object.
Thanks in advance for any help on this.
Greg
|