1

My team made a decision not to remove entries from database, but to give them a status like ACTIVE or DELETED.

Problem arises when, for entity - let's call it Customer I make a collection of another entities:

@Entity
public class Customer {
    @ManyToMany
    private List<Order> orders;

    private MyEnumStatus status;

    ...
}

If I want to 'remove' one order from the list orders I have no influence on how is it done (especially - it will certainly not set desired status on entry in the link table and instead it will just remove a record from it).

@PersistenceContext 
EntityManager em;

...

Customer customer = customerService.getRandomOne();
customer.getOrders().remove(0);
em.merge(customer);

My question is - is it possible to apply a status field (in Order entity) to this scenario? I mean to somehow overwrite this behaviour to set statuses instead of removing entries.

Maciej Dobrowolski
  • 11,561
  • 5
  • 45
  • 67

3 Answers3

1

You need to implement logical deletes. See this answer for more information.

Community
  • 1
  • 1
mdatwood
  • 98
  • 1
  • 5
1

Yes it is.

You can use either Events or Interceptors. Both are described in chapter 14 of the reference docs. This option is powerful but hairy. Play with it at your own risk.

Soft deletes are probably a better option. @mdatwood's link shows one way of doing this. There's a fuller example at feraturenotbug. Don't forget to tweak all your queries return only objects that aren't deleted. That's mentioned in the example.

Paul Hicks
  • 13,289
  • 5
  • 51
  • 78
1

You can override the remove() method implementation using the @SQLDelete annotation as below in your customer entity:

@Entity
@SQLDelete(sql="UPDATE customer SET status = 'deleted' WHERE id = ?")
public class Customer {
    @ManyToMany
    private List<Order> orders;

}
18bytes
  • 5,951
  • 7
  • 42
  • 69