CodexBloom - Programming Q&A Platform

Hibernate not updating a nested entity correctly in a @ManyToOne relationship with cascading operations

👀 Views: 0 đŸ’Ŧ Answers: 1 📅 Created: 2025-06-17
hibernate jpa spring Java

I'm collaborating on a project where I'm having a hard time understanding I'm experiencing an issue where Hibernate is not correctly updating a nested entity in a @ManyToOne relationship even though I've set cascade operations... I've defined my entities like this: ```java @Entity public class Order { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String orderNumber; @ManyToOne(cascade = CascadeType.ALL) private Customer customer; } @Entity public class Customer { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String name; @OneToMany(mappedBy = "customer", cascade = CascadeType.ALL) private List<Order> orders; } ``` When I attempt to update an existing `Order` object and set a new `Customer` object, it seems that Hibernate does not persist the changes to the `Customer`. Here's the code I've been using to perform the update: ```java @Transactional public void updateOrder(Long orderId, String newOrderNumber, Long customerId, String customerName) { Order order = entityManager.find(Order.class, orderId); order.setOrderNumber(newOrderNumber); Customer customer = new Customer(); customer.setId(customerId); customer.setName(customerName); order.setCustomer(customer); entityManager.merge(order); } ``` When I check the database after this update, the `Customer` details do not reflect the changes even though the `Order` is updated. The SQL logs indicate that the `Customer` update operation isn't being executed. I also tried using `CascadeType.PERSIST` and `CascadeType.MERGE` separately for the `customer` relationship, but I still faced the same issue. I would appreciate any insights on why the nested `Customer` entity isn't being persisted properly and what steps I can take to ensure that the changes are reflected in the database. I'm using Hibernate 5.4.30 and Spring 5.3.12. Thank you in advance for your help! How would you solve this?