@IdClass - JPA Annotation

The @IdClass annotation is used if the current entity defined a composite identifier. A separate class encapsulates all the identifier attributes, which are mirrored by the current entity mapping.

The IdClass Annotation Example

Let's say we have a table called Account and it has two columns – accountNumber, accountType – that form the composite key. Now we have to map it in JPA.

As per the JPA specification, let's create an AccountId class with these primary key fields:

public class AccountId implements Serializable {
    private String accountNumber;
 
    private String accountType;
 
    // default constructor
 
    public AccountId(String accountNumber, String accountType) {
        this.accountNumber = accountNumber;
        this.accountType = accountType;
    }
 
    // equals() and hashCode()
}

Next, let's associate the AccountId class with the entity Account.

In order to do that, we need to annotate the entity with the @IdClass annotation. We must also declare the fields from the AccountId class in the entity Account and annotate them with @Id:

@Entity
@IdClass(AccountId.class)
public class Account {
    @Id
    private String accountNumber;
 
    @Id
    private String accountType;
 
    // other fields, getters and setters
}

The class which is annotated with @IdClass annotation specifies a composite primary key class that is mapped to multiple fields or properties of the entity.

The names of the fields or properties in the primary key class and the primary key fields or properties of the entity must correspond and their types must be the same.

References

https://javaee.github.io/javaee-spec/javadocs/javax/persistence/IdClass.html

Comments