Questo contenuto non è disponibile nella lingua selezionata.
1.2.4. Collection of values
Let us add a collection of email addresses to the
Person
entity. This will be represented as a java.util.Set
of java.lang.String
instances:
The mapping of this
Set
is as follows:
<set name="emailAddresses" table="PERSON_EMAIL_ADDR"> <key column="PERSON_ID"/> <element type="string" column="EMAIL_ADDR"/> </set>
<set name="emailAddresses" table="PERSON_EMAIL_ADDR">
<key column="PERSON_ID"/>
<element type="string" column="EMAIL_ADDR"/>
</set>
The difference compared with the earlier mapping is the use of the
element
part which tells Hibernate that the collection does not contain references to another entity, but is rather a collection whose elements are values types, here specifically of type string
. The lowercase name tells you it is a Hibernate mapping type/converter. Again the table
attribute of the set
element determines the table name for the collection. The key
element defines the foreign-key column name in the collection table. The column
attribute in the element
element defines the column name where the email address values will actually be stored.
Here is the updated schema:
You can see that the primary key of the collection table is in fact a composite key that uses both columns. This also implies that there cannot be duplicate email addresses per person, which is exactly the semantics we need for a set in Java.
You can now try to add elements to this collection, just like we did before by linking persons and events. It is the same code in Java:
This time we did not use a fetch query to initialize the collection. Monitor the SQL log and try to optimize this with an eager fetch.