CodexBloom - Programming Q&A Platform

Hibernate 6.0: How to fix 'Duplicate entry for key' on saving a new entity with composite key?

πŸ‘€ Views: 67 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-14
hibernate jpa composite-key Java

I'm trying to configure I'm attempting to set up I'm trying to figure out I'm updating my dependencies and I'm encountering a frustrating issue while trying to save a new entity that has a composite key in Hibernate 6.0. The entity is structured as follows: ```java @Entity @IdClass(CompositeKey.class) public class Order { @Id private Long orderId; @Id private Long productId; private int quantity; // getters and setters } public class CompositeKey implements Serializable { private Long orderId; private Long productId; // equals and hashCode methods } ``` I have defined the composite key using `@IdClass`, and when I try to save a new `Order` object, I get the following error: ``` org.hibernate.exception.ConstraintViolationException: Duplicate entry '101-202' for key 'PRIMARY' ``` This indicates that Hibernate is attempting to insert a record that conflicts with an existing composite key in the database. To troubleshoot, I checked the database and confirmed that there is no existing entry with the same `orderId` and `productId`. Here’s the code snippet I’m using to save the entity: ```java Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); Order order = new Order(); order.setOrderId(101L); order.setProductId(202L); order.setQuantity(3); session.save(order); transaction.commit(); session.close(); ``` I’ve also made sure that the `CompositeKey` class correctly implements `equals` and `hashCode`. After investigating, I realized that I need to ensure the properties are unique across the database, as the error suggests there might be a conflict despite my checks. I even performed a query to check whether the combination already exists: ```sql SELECT * FROM orders WHERE order_id = 101 AND product_id = 202; ``` The result was empty, so I'm puzzled as to why Hibernate thinks I'm trying to insert a duplicate. Is there a possibility that the session is not clearing correctly or that somehow stale data is being used from a previous transaction? Are there any specific configurations in Hibernate 6.0 I should check to ensure that composite keys behave as expected? Any guidance would be greatly appreciated! I'm developing on Debian with Java. Any examples would be super helpful. I'm working in a macOS environment. Has anyone dealt with something similar? I'd really appreciate any guidance on this.