ToString, circular references and Hibernate
I have been writing some Hibernate code and in order to check what is going on with the mappings and the data they actually retrieve, all my domain objects implement org.ckkloverdos.string.IToStringAware of ckkl-core.
The actual domain model does not matter for this post, but let’s say that two of my classes are Person and Address and the association is such that a Person has one or more Addresses (under the hoods there are 3 tables, 2 for the entities and one join table). Also, an Address object has a reference to the Person it belongs to.
Here is a printout an Addresses list:
ArrayList[
0=Address(
name="Some address 1"
person=null
addressId=4)
1=Address(
name="Some address 2"
person=null
addressId=3)
2=<REF:1>Address(
name="The Master Address"
person=Person$$EnhancerByCGLIB$$e8f89ce1(
addresses=PersistentSet[0=<@REF:1>]
name="The Master Person"
personId=1)
addressId=1)
... ]
So, actually, I can verify that I have one Person (”The Master Person”) to which one Address (”The Master Address”) belongs to. Notice how this Address lists its Person, which in turn has a circular reference to the particular Address.
Do not get confused by the domain object model. It actually does not matter. The idea here is that ToString can correctly report a circular reference in my object graph. It can also index those circular references in order of appearance, so that you will see <REF:1>, <REF:2> and so on, and of course the respective back-references <@REF:1>, <@REF:2> and so on.
<REF:n> marks a reference and <@REF:n> designates a circular (back) reference to the point where <REF:n> appeared. So, at the example above, we mark the particular Address having index 2 in the ArrayList because its object is also used in one of its properties, the Person.
One little bonus, as a side-effect of using the ToString mini-framework, is that I can see what Hibernate does under the hood, by noticing the name of the class
Person$$EnhancerByCGLIB$$e8f89ce1
Well, that’s nice!