Java Reference
In-Depth Information
Mapping Collections
In Figure 7-4, we show the User objects as having an unknown number of Advert instances. In
the database, this is then represented with three tables, one of which is a link table between
the two entity tables.
Figure 7-4. Mapping collections
The Java collection classes provide the most elegant mechanism for expressing the
“many” end of a many-to-many relationship in our own classes:
public Set getAdverts();
If we use generics, we can give an even more precise specification:
public Set<Advert> getAdverts();
n Note A lot of legacy code will not use generics. However, if you have the opportunity you should do so,
as it allows you to make this sort of distinction clear at the API level, instead of at the documentation level.
Hibernate 3 is compatible with Java 5 generics.
Of course, we can place values (of Object type) into collections as well as entities, and Java
5 introduced autoboxing so that we have the illusion of being able to place primitives into
them as well.
List<Integer> ages = getAges();
int first = ages.get(0);
The only catch with collection mapping is that an additional table may be required to cor-
rectly express the relationship between the owning table and the collection. Table 7-21 shows
how it should be done; the entity table contains only its own attributes.
Search WWH ::




Custom Search