If you've fully embraced our view that composite keys are a bad thing and that entities should have synthetic identifiers (surrogate keys), then you might find it a bit odd that the many to many associations and collections of values that we've shown so far all map to tables with composite keys! Now, this point is quite arguable; a pure association table doesn't seem to benefit much from a surrogate key (though a collection of composite values
might
). Nevertheless, Hibernate provides a feature that allows you to map many to many associations and collections of values to a table with a surrogate key.
The <idbag>
element lets you map a List
(or Collection
) with bag semantics.
<idbag name="lovers" table="LOVERS">
<collection-id column="ID" type="long">
<generator class="sequence"/>
</collection-id>
<key column="PERSON1"/>
<many-to-many column="PERSON2" class="Person" fetch="join"/>
</idbag>
As you can see, an <idbag>
has a synthetic id generator, just like an entity class! A different surrogate key is assigned to each collection row. Hibernate does not provide any mechanism to discover the surrogate key value of a particular row, however.
Note that the update performance of an <idbag>
is
much
better than a regular <bag>
! Hibernate can locate individual rows efficiently and update or delete them individually, just like a list, map or set.
In the current implementation, the native
identifier generation strategy is not supported for <idbag>
collection identifiers.