5.5. Reflexive Associations

It's also possible for objects and tables to have associations back to themselves. This supports persistent recursive data structures like trees, in which nodes link to other nodes. Tracing through a database table storing such relationships using a SQL query interface is a major chore. Luckily, once it's mapped to Java objects, the process is much more readable and natural.

One way we might use a reflexive link in our music database is to allow alternate names for artists. This is useful more often than you might expect, because it makes it very easy to let the user find either "The Smiths" or "Smiths, The" depending on how they're thinking of the group, with little code, and in a language-independent way.

I mean human language here, English versus Spanish or something else. Put the links in the data rather than trying to write tricky code to guess when an artist name should be permuted.

5.1.1. How do I do that?

All that's needed is to add another field to the Artist mapping in Artist.hbm.xml, establishing a link back to Artist. Example 5-13 shows one option.

Example 5-13. Supporting a reflexive association in the Artist class
<many-to-one name="actualArtist" class="com.oreilly.hh.Artist">
  <meta attribute="use-in-tostring">true</meta>
</many-to-one>

This gives us an actualArtist property that we can set to the id of the "definitive" Artist record when we're setting up an alternate name. For example, our "The Smiths" record might have id 5, and its actualArtist ...

Get Hibernate: A Developer's Notebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.