Annotation Interface MapsId


@Target({METHOD,FIELD}) @Retention(RUNTIME) public @interface MapsId
Designates a ManyToOne or OneToOne relationship attribute that provides the mapping for
  • an Id or EmbeddedId attribute of an entity with a derived identity, or
  • an attribute of the EmbeddedId class of an entity with a derived identity.

The value() element specifies the attribute within a composite key to which the relationship attribute corresponds. If the primary key of the entity is of the same Java type as the primary key of the entity referenced by the relationship, the value attribute is not specified.

In this example, the parent entity has simple primary key:

@Entity
class Employee {

    @Id
    long id;

    String name;

    ...
}

And then the dependent entity uses EmbeddedId to declare its composite primary key:

@Embeddable
class PaycheckId {
    int period;
    long empId;  // agrees with primary key type of Employee
}

@Entity
class Paycheck {

    @EmbeddedId
    PaycheckId id;

    @MapsId("empId")  // maps the empId attribute of PaycheckId
    @ManyToOne
    Employee emp;

    ...
}

Alternatively, the dependent entity may use IdClass to declare its composite primary key:

class PaycheckId {
    int period;
    long empId;  // agrees with empId field of Paycheck
}

@Entity
@IdClass(PaycheckId.class)
class Paycheck {

    @Id
    int period;

    @Id
    long empId;  // agrees with primary key type of Employee

    @MapsId("empId")  // maps the empId attribute
    @ManyToOne
    Employee emp;

    ...
}

If a ManyToOne or OneToOne relationship declared by a dependent entity is annotated MapsId, an instance of the entity cannot be made persistent until the relationship has been assigned a reference to an instance of the parent entity, since the identity of the dependent entity declaring the relationship is derived from the referenced parent entity.

Since:
2.0
  • Optional Element Summary

    Optional Elements
    Modifier and Type
    Optional Element
    Description
    (Optional) The name of the attribute within the composite key to which the relationship attribute corresponds.
  • Element Details

    • value

      String value
      (Optional) The name of the attribute within the composite key to which the relationship attribute corresponds. If not explicitly specified, the relationship maps the primary key of the entity.
      Default:
      ""