Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update an Entity after another Entity update in Spring Data? [duplicate]

I need to perform an Update to an entity after another related entity is updated.

I have two entities: OrderEntity and CustomerOrderEntity, in a relation of 1:N. Both have an status field. OrderEntity status depends of all children's status field. So, if one CustomerOrderEntity is updated, I need to recalculate the new status of OrderEntity and persist/update it.

I have implemented a listener:

public class CustomerOrderEntityEnventHandler {

    private OrderService orderService;

    @PostUpdate
    public void handleAfterSave(CustomerOrderEntity customerOrder) {
        OrderEntity order = customerOrder.getOrder();
        OrderStatus newStatus = calculateNewStatus(order);
        order.setStatus(newStatus);
    }

        //other methods and DI handler for orderService. The injection is fine.
}

The listener is annotated in CustomerOrderEntity and it is being called properly. However, after the process is completed, OrderEntity remains the old status even the orderRepository.save() is called with the correct new status.

I expect orderEntity to be updated with new status.

UPDATE:
I change the implementation to use PostUpdateEventListener. It is being invoked properly, however, the "other" entity is not being updated still.

public class CustomerOrderEntityUpdateEnventListener implements PostUpdateEventListener {
    @Override
    public void onPostUpdate(PostUpdateEvent event) {
        if (event.getEntity() instanceof CustomerOrderEntity) {

            Session session = event.getSession();
            CustomerOrderEntity customerOrder = (CustomerOrderEntity) event.getEntity();
            OrderEntity order = customerOrder.getOrder();
            OrderStatus newStatus = calculateNewStatus(order);
            order.setStatus(newStatus);

            session.saveOrUpdate(order);
        }
    }

//other methods
}

Note that the updated entity is CustomerOrderEntity and I want to update OrderEntity.

like image 767
lordneru Avatar asked Oct 26 '25 05:10

lordneru


1 Answers

I don't think it will work for other entities. JPA specification says the following:

In general, the lifecycle method of a portable application should not invoke EntityManager or query operations, access other entity instances, or modify relationships within the same persistence context. A lifecycle callback method may modify the non-relationship state of the entity on which it is invoked.

like image 87
H Pat Avatar answered Oct 27 '25 20:10

H Pat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!