Skip to main content

Notice: this Wiki will be going read only early in 2024 and edits will no longer be possible. Please see: for the plan.

Jump to: navigation, search


How to use derived identifiers to map composite Ids through ManyToOne relationships

Defining an Id for a OneToOne or ManyToOne in JPA 2.0 is much simpler. The @Id annotation or id XML attribute can be added to a OneToOne or ManyToOne mapping. The Id used for the object will be derived from the target object's Id. If the Id is a single value, then the source object's Id is the same as the target object's Id. If it is a composite Id, then the IdClass will contain the Basic Id attributes, and the target object's Id as the relationship value. If the target object also has a composite Id, then the source object's IdClass will contain the target object's IdClass.

Example JPA 2.0 ManyToOne id annotation

public class Phone {
    private String type;
    @JoinColumn(name="OWNER_ID", referencedColumnName="EMP_ID")
    private Employee owner;

Example JPA 2.0 ManyToOne id XML

<entity name="Phone" class="org.acme.Phone" access="FIELD">
    <id-class class="org.acme.PhonePK"/>
    <id name="type"/>
    <many-to-one name="owner" id="true">
        <join-column name="OWNER_ID" referencedColumnName="EMP_ID"/>

Example JPA 2.0 id class

public class PhonePK {
    private String type;
    private long owner;
    public PhonePK() {}
    public PhonePK(String type, long owner) {
        this.type = type;
        this.owner = owner;
    public boolean equals(Object object) {
        if (object instanceof PhonePK) {
            PhonePK pk = (PhonePK)object;
            return type.equals(pk.type) && owner == pk.owner;
        } else {
            return false;
    public int hashCode() {
        return type + owner;

Back to the top