A2oz

What is an Embedded ID in Hibernate?

Published in Database 2 mins read

An embedded ID in Hibernate is a way to represent a composite primary key for an entity using a single attribute. This attribute is an object that encapsulates multiple fields that together uniquely identify an entity.

Here's a breakdown:

  • Composite Primary Key: In databases, a composite primary key consists of multiple columns that work together to uniquely identify a row.
  • Embedded ID in Hibernate: Hibernate provides the concept of an embedded ID to map this composite primary key to an object in your Java code.
  • Benefits of Embedded IDs:
    • Clean Code: Instead of handling multiple fields individually, you have a single object representing the composite key.
    • Encapsulation: The embedded ID object encapsulates the logic for generating and comparing composite keys.
  • Example:
    • Let's say you have an entity called Order with a composite primary key consisting of orderId and customerId.
    • You can create an embedded ID class called OrderIdentifier containing these fields.
    • The Order entity will have an attribute of type OrderIdentifier as its primary key.

Code Example:

@Embeddable
public class OrderIdentifier {

    private int orderId;
    private int customerId;

    // Getters and Setters
}

@Entity
public class Order {

    @EmbeddedId
    private OrderIdentifier id;

    // Other attributes
}

In this example:

  • @Embeddable annotation marks the OrderIdentifier class as an embedded ID.
  • @EmbeddedId annotation on the id field in the Order entity indicates that it's an embedded ID.

Hibernate will automatically handle the mapping of the composite key fields to the database table using the embedded ID object. This simplifies the code and makes it easier to work with composite keys.

Related Articles