Mapping components

We consider a simple example. We may add an email property to session3.User:

...
public class User {
  ...
  private Email address; ...

Why do we use a separate class Email rather than a simple private String email declaration? The answer is quite simple: We want Email instances to be extensible and allow for method definitions like sendEmail(...):

public class Email {

  private String emailAddress;
  ...
  void sendEmail(final String subject, final String content) {}
}

Our Email class may of course have more than just one property. We don't want to email addresses to be database entities themselves. Instead they are meant to be components of User instances. This is achieved by:

Annotate class Email to be embeddable:
package component.email;

@Embeddable public class Email {

    private String emailAddress;
    ...
}
Annotate emailAddress to become an embedded property:
package component.email;
     ...
public class User {

     private Email address;
     @Embedded
     public Email getEmailAddress() { return address;}
     ...

We may now persist component.email.User instances:

em.getTransaction().begin();
{
   final User u = new User(123, "goik", "Martin Goik");
   u.setEmailAddress(new Email("goik@hdm-stuttgart.de"));
   em.persist(u);
}
em.getTransaction().commit();

exercise No. 25

Home and work address

Q:

Consider the following sketch of an Address class:

public class Address {

  private String street;
  private String city;
  private String zipcode;
  ...
}

Extend this example to allow for two properties homeAddress and workAddress of type Address. You will encounter a problem concerning conflicting database attribute names. Resolution is possible using @javax.persistence.AttributeOverrides declarations.

A:

See component.address.Address and component.address.User.

Q:

Load a User instance from your database and demonstrate that changes to this existing persistent object component's values get persisted.

A:

See component.address.ModifyWorkAddress.