CodexBloom - Programming Q&A Platform

Hibernate not properly mapping composite keys leading to Duplicate Key handling

👀 Views: 28 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-17
hibernate spring-boot postgresql java

Quick question that's been bugging me - I'm working with a `DuplicateKeyException` when trying to continue entities with composite primary keys in Hibernate. My setup involves a Spring Boot application using Hibernate ORM 5.4.30.Final and PostgreSQL 12. The entity classes are structured as follows: ```java @Entity @IdClass(OrderId.class) public class Order { @Id private Long orderId; @Id private Long productId; private int quantity; // Getters and setters } public class OrderId implements Serializable { private Long orderId; private Long productId; // Getters, setters, equals, and hashCode } ``` When I attempt to save an `Order` instance like so: ```java Order order = new Order(); order.setOrderId(1L); order.setProductId(2L); order.setQuantity(10); orderRepository.save(order); ``` I get this behavior message: ``` org.springframework.dao.DuplicateKeyException: Failed to execute JdbcTemplate.update; SQL [insert into order (order_id, product_id, quantity) values (?, ?, ?)]; duplicate key value violates unique constraint "order_pkey"; nested exception is org.postgresql.util.PSQLException: behavior: duplicate key value violates unique constraint "order_pkey" ``` I've double-checked that the keys generated by my application should be unique, so I'm puzzled as to why this is happening. My database table is defined as: ```sql CREATE TABLE order ( order_id bigint NOT NULL, product_id bigint NOT NULL, quantity integer, PRIMARY KEY (order_id, product_id) ); ``` I've also tried adding a `@GeneratedValue` annotation to the `orderId`, but since both are composite keys, I'm not sure it's appropriate. I'm not using any batching or multi-threading that could interfere with the insert operations. Is there something I'm missing regarding the configuration of composite keys in Hibernate, or how I might ensure that the keys are generated correctly and handled properly? Any help would be greatly appreciated! This is part of a larger CLI tool I'm building. I'd really appreciate any guidance on this. I'm using Java latest in this project. Any feedback is welcome!