4.7. Embedded Objects

An embedded object is one that is wholly owned by a parent entity, in the UML compositional ("colour in the black diamond") sense. Using domain-driven design terminology it is an aggregated object (with its owning entity the aggregate root).

The @javax.persistence.Embeddable annotation defines an embedded object, that is, a class whose instances are stored as an intrinsic part of an owning entity and share the identity of the entity. Note that @Embeddable entities must not also be annotated with @Entity. They also do not have an @Id. That's because each of the persistent properties of the embedded object is mapped to the database table for the entity. JPA restricts the embedded objects to only consisting of @Basic (value) properties.

Having defined an embeddable class, the owning entity defines an association using the @javax.persistence.Embeddable annotation. In Naked Objects terms this is a property whose return type is the @Embeddable class. For example, consider an Address class:

@Embeddable
public class Address {

    private Integer houseNumber;
    @Basic
    public Integer getHouseNumber() { ... }
    public void setHouseNumber(Integer houseNumber) { ... }

    private String streetName;
    @Basic
    public String getStreetName() { ... }
    public void setStreetName(Integer streetName) { ... }

    ...
}

The owning root Customer entity might look like:

@Entity
@DiscriminatorValue("CUS")
public class Customer {

    private Integer id;
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    public Integer getId() { ... }
    private void setId(Integer id) { ... }

    private Address address;
    @Embedded
    public Address getAddress() { ... }
    ...
}

Although JPA defines the @EmbeddedId annotation (to indicate a property whose type represents a composite primary key that is an embeddable class), JPA Objects does not support this (because in JPA Objects all primary keys must be simple, not composite).