Sets and lists

Users may have multiple email addresses:

public class User {

	  Set<Email> email;
	  ...

Using embedded values we need an @ElementCollection declaration to achieve a proper mapping:

package component.emails;
	  ...
	  public class User {
	  ...
	  private Set<Email> emails = new HashSet<Email>();
	  @ElementCollection 
	  public Set<Email> getEmails() { return emails; }
	  ...

This will map component.emails.Email entries in a separate table:

package component.emails;
	  ...
	  public class PersistUser {
	  public static void main(String[] args) {
	  final Session session = HibernateUtil.createSessionFactory("component/emails/hibernate.cfg.xml").openSession();
	  {
          final Transaction transaction = session.beginTransaction();
          final User u = new User(123, "goik", "Martin Goik");
          u.getEmails().add(new Email("goik@hdm-stuttgart.de"));
          u.getEmails().add(new Email("goma@someserver.org"));
          session.save(u);
          transaction.commit();
	  } ...

exercise No. 26

Searching users by email components

Q:

Create a HQL query searching for:

  • All Users having an email address .

  • All users having at least two email addresses.

You may want to use a Hibernate Console to develop the appropriate queries.

exercise No. 27

Embedded postal addresses

Q:

Construct a corresponding example allowing session3.User instances to have a set of embedded component.address.Address elements.

exercise No. 28

Life cycle of parents and components

Q:

What happens, if an owning User instance gets deleted? Are composed Email or Address values are implicitly being deleted as well?

exercise No. 29

Ordered components

Q:

Replace java.util.Set by java.util.List and assure that the order of components is being preserved in a JPA 2 compliant manner.