Junior — Middle
Have you used composite keys when working with Hibernate?
sobes.tech AI
Answer from AI
In Hibernate, composite keys are used to identify an entity using multiple fields instead of a single one. This is necessary when the unique identifier of an object is formed from a combination of several attributes.
To implement a composite key in Hibernate, a separate class is usually created, which implements Serializable and contains all the key fields. This class is used with the @Embeddable annotation or as @IdClass.
Example using @Embeddable:
@Embeddable
public class OrderItemId implements Serializable {
private Long orderId;
private Long productId;
// constructors, equals, hashCode
}
@Entity
public class OrderItem {
@EmbeddedId
private OrderItemId id;
private int quantity;
// other fields and methods
}
Thus, Hibernate understands that the entity's identifier consists of multiple fields and works correctly with them during saving and searching.