Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To save an entity with @EmbeddedId as its primary key in Hibernate, you can follow these steps:

  1. Create the entity class with @EmbeddedId annotation and embeddable class with @Embeddable annotation.

  2. Create an instance of the entity class with the embedded primary key object set.

  3. Use the Session object's save() method to save the entity object to the database.

Example:

@Entity public class Order {

@EmbeddedId private OrderId id;

// other fields and methods...

}

@Embeddable public class OrderId implements Serializable {

@Column(name = "order_number") private String orderNumber;

@Column(name = "customer_id") private Long customerId;

// constructors, getters, and setters...

}

// to save an Order entity with a new orderNumber and customerId: OrderId id = new OrderId("12345", 1L); Order order = new Order(); order.setId(id); session.save(order);

// to update an existing Order entity: Order order = session.get(Order.class, new OrderId("12345", 1L)); order.setSomeField("new value"); session.save(order);