Chapter 4. Collections and Associations
No, this isn’t about taxes or politics. Now that we’ve seen how easy it is to get individual objects into and out of a database, it’s time to see how to work with groups and relationships between objects. Happily, it’s no more difficult.
Mapping Collections
In any real application you’ll be managing lists and groups of things. Java provides a healthy and useful set of library classes to help with this: the Collections utilities. Hibernate provides natural ways for mapping database relationships onto Collections, which are usually very convenient. You do need to be aware of a couple semantic mismatches, generally minor. The biggest is the fact that Collections don’t provide “bag” semantics, which might frustrate some experienced database designers. This gap isn’t Hibernate’s fault, and it even makes some effort to work around the issue.
Note
Bags are like sets, except that the same value can appear more than once.
Enough abstraction! The Hibernate reference manual does a good job
of discussing the whole bag issue, so let’s leave it and look at a working
example of mapping a collection where the relational and Java models fit
nicely. It might seem natural to build on the Track
examples from Chapter 2 and group them into albums, but that’s not the simplest place to start, because organizing an album involves tracking additional information, like the disc on which the track is found (for multidisc albums), and other such finicky details. So let’s add ...