CodexBloom - Programming Q&A Platform

Spring Data JPA with Composite Keys: Issues Persisting Data with @EmbeddedId

πŸ‘€ Views: 293 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-15
spring-boot spring-data-jpa hibernate Java

This might be a silly question, but I'm having trouble persisting entities that use a composite key with `@EmbeddedId` in Spring Data JPA... I have a class `OrderId` defined as the composite key, which contains two fields: `orderNumber` and `customerId`. My entity class `Order` is using this composite key as follows: ```java @Embeddable public class OrderId implements Serializable { private String orderNumber; private String customerId; // getters, setters, equals, hashCode } @Entity public class Order { @EmbeddedId private OrderId id; private String product; // getters, setters } ``` When I try to save a new order, I'm getting an `EntityNotFoundException` saying that the entity with the specified composite key want to be found, even though the keys I'm using should be new. Here’s how I’m trying to save the `Order`: ```java Order order = new Order(); OrderId orderId = new OrderId(); orderId.setOrderNumber("123456"); orderId.setCustomerId("cust001"); order.setId(orderId); order.setProduct("Laptop"); orderRepository.save(order); ``` I also have the repository set up like this: ```java public interface OrderRepository extends JpaRepository<Order, OrderId> { } ``` I've verified that the `equals` and `hashCode` methods in the `OrderId` class are implemented correctly, but I'm still working with this scenario. I’ve also tried adding `@GeneratedValue` to the composite key fields, but that doesn't seem to work since they are supposed to be a combination of existing values, not auto-generated. Am I missing something in the configuration, or is there something specific related to composite keys in Spring Data JPA that I need to be aware of? Any help would be greatly appreciated! I'm on Ubuntu 22.04 using the latest version of Java. Am I approaching this the right way?