CodexBloom - Programming Q&A Platform

Unexpected Duplicate Entries in Hibernate with Composite Keys in @Embeddable Class

šŸ‘€ Views: 54 šŸ’¬ Answers: 1 šŸ“… Created: 2025-06-17
hibernate spring-boot jpa java

I'm facing an issue where Hibernate is persisting duplicate entries when I'm using an @Embeddable class as a composite key in my entity... Despite having proper primary key constraints in the database, I still see multiple entries with the same composite key values appearing. Here's a simplified version of my setup. I have an `Order` entity that uses a composite key defined by an `OrderId` class: ```java @Entity @IdClass(OrderId.class) public class Order { @Id private String productId; @Id private String customerId; private int quantity; // getters and setters } @Embeddable public class OrderId implements Serializable { private String productId; private String customerId; // equals and hashCode implementations } ``` When I try to save an `Order`, I call: ```java Order order = new Order(); order.setProductId("P123"); order.setCustomerId("C456"); order.setQuantity(2); session.save(order); ``` However, if I run the save operation again with the same `productId` and `customerId`, instead of throwing an exception or ignoring the operation, it creates another entry in the database. I have also tried using `session.merge(order)` instead of `session.save(order)`, but that doesn't seem to make a difference. In my `OrderId` class, I've implemented `equals()` and `hashCode()` based on both fields: ```java @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof OrderId)) return false; OrderId that = (OrderId) o; return Objects.equals(productId, that.productId) && Objects.equals(customerId, that.customerId); } @Override public int hashCode() { return Objects.hash(productId, customerId); } ``` I've checked my Hibernate configuration as well, and it looks fine. I’m using Hibernate version 5.4.30.Final with Spring Boot 2.4.5. The database is PostgreSQL 13.1. I've tried to see if any transactions are interfering, but the duplicates still appear even when transactions are managed properly. Am I missing something in the configuration or is there a specific way to handle composite keys that I should be aware of? Any help would be greatly appreciated! What are your experiences with this? Any ideas what could be causing this?