7. Top-level Collections
Definition: A top-level collection is a collection defined outside of the scope of an individual class and available for use in all classes in the mapping files.
Scenario: We have one first-rank class, Foo, and a collection of Strings (e.g. people's names) which we wish to make available to other classes without constantly declaring set definitions inside each one.
Hibernate Mapping:
In Hibernate, this could be mapped as follows:
Note that a top-level collection needs its own key generator, and that this cannot be of the assigned type since it is never exposed to a calling application.
Table Schema:
Again, Person does not represents a first-rank class. It is simply a collection of second-rank persistent objects - in this case Strings. Note also that Names simply has id not foo_id. This is to allow it to be used by a variety of first-rank classes. Also, because we cannot use Person's id as a foo_id, we have added a person_id FK to Foo.
Bidirectionality:
There's no bidirectional relationship available here as there is only one first-rank class involved.
Definition: A top-level collection is a collection defined outside of the scope of an individual class and available for use in all classes in the mapping files.
Scenario: We have one first-rank class, Foo, and a collection of Strings (e.g. people's names) which we wish to make available to other classes without constantly declaring set definitions inside each one.
|
Set Foo.getNames() // returns a collection of String instances |
Hibernate Mapping:
In Hibernate, this could be mapped as follows:
|
<set role="names" table="names"> <key column="id" type="string"> <generator class="uuid.hex"/> </key> <element column="name" type="string"/> </set> <class name="Foo" table="foo"> ... <collection name="names" column="name_id" role="names"/> </class> |
Note that a top-level collection needs its own key generator, and that this cannot be of the assigned type since it is never exposed to a calling application.
Table Schema:
|
Foo |
|
|
id |
person_id |
|
Person |
|
|
id |
name |
Again, Person does not represents a first-rank class. It is simply a collection of second-rank persistent objects - in this case Strings. Note also that Names simply has id not foo_id. This is to allow it to be used by a variety of first-rank classes. Also, because we cannot use Person's id as a foo_id, we have added a person_id FK to Foo.
Bidirectionality:
There's no bidirectional relationship available here as there is only one first-rank class involved.
