Composite Primary Key

In some cases, you may want to define a composite primary key, rather than a simple primary key. A composite primary key must correspond to two or more persistent fields or properties. The EJB3 cartridge allows the creation of a composite primary key class to satisfy this requirement.

To map two or more attributes of an entity POJO as a property of a composite primary key, simply model the <<Identifier>> stereotype on the corresponding attributes in the entity. The order of the primary keys is defined by the order of the attribute identifiers in the entity.

The following example introduces a composite primary key for the Car entity.

images/org/andromda/test/4/a/uml.gif

  • Auto-generated source that does not need manual editing
  • Auto-generated source that should be edited manually
  • File that is affected by the modifications applied in this section

The EJB3 cartridge represents a composite primary key as an embeddable class, implements Serializable and defines the equals and hashCode methods. The CarPK embeddable composite primary key class has the @javax.persistence.Embeddable annotation. The CarEmbeddable class contains the corresponding @javax.persistence.EmbeddedId annotation on the composite primary key getter. Notice how the @javax.persistence.AttributeOverrides annotation is used to map the primary key attributes to the relational database columns in CarEmbeddable.java.

The CarDaoBase class accounts for the composite PK in the load and remove operations. TODO: To improve on this, add further operations to the DAO components to have the PK class as an argument rather than the individual attributes that form the PK.

The following example illustrates the effect of having a composite primary key on the inverse side of a relationship. What's important here is the @javax.persistence.JoinColumns annotation on getOwner() in CarEmbeddable.java. Because Person has a composite primary key, the foreign key on Many-To-One owning side has to know about this.

images/org/andromda/test/4/b/uml.gif

  • Auto-generated source that does not need manual editing
  • Auto-generated source that should be edited manually
  • File that is affected by the modifications applied in this section

Currently, the EJB3 cartridge will disable the findByPrimaryKey generic finder for an entity with a composite primary key.

Next

In the next section, we will learn how to model enumerations, click here.