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
.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.