How to soft delete a child entity to allow the client to review it before it finally gets deleted


#1

Hi,

I have a process of Orders where I load Order and all their OrdemItem, and I’m having problems with this situation:

Order: PK[id = 1];

OrderItem: PK[order_id = 1, order_line = 1];
OrderItem: PK[order_id = 1, order_line = 2];

So I remove the Object (OrderItem: PK[order_id = 1, order_line = 1]), only in collection because I don’t want to delete in database before the user confirm the whole process. But for any reason the user add the same OrderItem again in the collection.

If I merge the father (Order) after that I’m getting:

A different object with the same identifier value was already associated with the session

If I remove the OrderItem in database when I remove it from the collection it works, but I want to keep it in the database because the user could abort the process.

Is there any elegant approach to do this with Hibernate? Or should I do a workaround with @Transient attribute or another collection?

Thanks in advance


#2

That doesn’t happen with merge, but with Session#update or Session#saveOrUpdate.

If I remove the OrderItem in database when I remove it from the collection it works, but I want to keep it in the database because the user could abort the process.

You need to use a state property in this case which is an Enum and takes values like:

  • VALID
  • REMOVING
  • REMOVED

This way you can allow the user to review it prior to finally deleting it or changing it to the REMOVED state.

Is there any elegant approach to do this with Hibernate? Or should I do a workaround with @Transient attribute or another collection?

There’s always an elegant solution with JPA and Hibernate. In this case, you could use the Hibernate @Filter to dynamically load the OrderItem based on their status. For more details, check out the User Guide.


#3

Thank you, I’ll check and use @Filter