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:
private Set emailAddresses = new HashSet(); public Set getEmailAddresses() { return emailAddresses; } public void setEmailAddresses(Set emailAddresses) { this.emailAddresses = emailAddresses; }
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>
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:
_____________ __________________ | | | | _____________ | EVENTS | | PERSON_EVENT | | | ___________________ |_____________| |__________________| | PERSON | | | | | | | |_____________| | PERSON_EMAIL_ADDR | | *EVENT_ID | <--> | *EVENT_ID | | | |___________________| | EVENT_DATE | | *PERSON_ID | <--> | *PERSON_ID | <--> | *PERSON_ID | | TITLE | |__________________| | AGE | | *EMAIL_ADDR | |_____________| | FIRSTNAME | |___________________| | LASTNAME | |_____________|
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:
private void addEmailToPerson(Long personId, String emailAddress) { Session session = HibernateUtil.getSessionFactory().getCurrentSession(); session.beginTransaction(); Person aPerson = (Person) session.load(Person.class, personId); // adding to the emailAddress collection might trigger a lazy load of the collection aPerson.getEmailAddresses().add(emailAddress); session.getTransaction().commit(); }
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.