I have two classes A and B. Class B has a reference to object of class A. Instantiating the classes into objects 'a' and 'b' respectively:
a --> b (object 'b' has a reference to object 'a')
I am using Castor to save these objects into XML document.
Referring to earlier information in the Castor documentation and mailing list, I noted that
"Castor supports references via the Source Code Generator and via the mapping file"
"References are not supported via introspection"
"We need to use the 'reference' and 'identity' in conjunction"
How I am doing it:-
This is how the classes appears:
Class A{
String id
...
getId() {...}
setId(String newId) {...}
}
Class B{
...
reference_to_A
...
getId() {...}
setId(String newId) {...}
getReference_to_A() {...}
setReference_to_A(A a) {...}
}
Dictionary id_names // stores ids of all objects
We need to use a mapping file, which uses the identity and reference in conjunction as follows:
A --> identity
B --> attribute A, reference=true
A snippet from the mapping file:
Mark the appropriate Identity field: (the field 'id' of class A)
<class name="A" identity="id">
...
<field name="id" type="string">
<bind-xml node="attribute"/>
</field>
...
</class>
Then mark references as such: (the 'reference' of <bind-xml> element is set as 'true' for the field 'reference_to_A')
<class name="B">
...
<field name=" reference_to_A" type="A">
<bind-xml node="attribute" reference="true"/>
</field>
...
</class>
During the marshalling of the objects into XML document, the reference to the object is stored as a string (in the mapping file, I have set 'reference=true' for this field).
During unmarshalling..
Apart from the above-mentioned accessors for the field 'reference_to_A', we need to add another method, which takes a 'String' argument. The new method looks as follows:
B.setReference_to_A (String id_of_a) {
Obj = Get_From_Dictionary(id_of_a) // lookup in the dictionary
if (Obj != null) {
Reference_to_parent_object = Obj
}
else {
error // Object not found
}
}
Kindly let me know if I have missed anything. Any comments, feedbacks, any other solutions(Castor or any other) are welcome.
Related Issue: Unmarshalling collection of references
If this code is correct, can someone insert this description in the Castor documentation?
Thanks
<http://www.calt.insead.edu/people/sunil/>
<http://www.insead.edu/facultyresearch/researchstaff/srachamadugu.cfm>
