4

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.

1
  • 1
    This may not answer your question, but the above is exactly why aggregate roots were invented. Commented Sep 8, 2019 at 21:21

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Oh, nice input. Do you know a workaround to achieve my requirement? Basically I need to "trigger" some services after a post, to keep both states synchronized.
Best option is to call both methods in same service method. Another option is database trigger. A third option is to use another Entity manager but it should be last resort.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.