Skip to Main Content
Hibernate: A Developer's Notebook
book

Hibernate: A Developer's Notebook

by James Elliott
May 2004
Intermediate to advanced content levelIntermediate to advanced
192 pages
4h 46m
English
O'Reilly Media, Inc.
Content preview from Hibernate: A Developer's Notebook

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Getting Started with Hibernate 3

Getting Started with Hibernate 3

James Elliott

Publisher Resources

ISBN: 0596006969Supplemental ContentCatalog PageErrata