I am trying to prevent an entity from being persisted without throwing an exception. Lets say that we have a table holding address rows called Address. In the Address Entity I have the following method:
@PrePersist
@PreUpdate
private void prePersist() {
if (areAllFieldsInTheEntityEmpty()) {
throw new PersistenceException("You can not save an empty address!");
}
}
Is there a way to prevent the address from being saved(so no row containing only nulls/empty string are inserted) without raising an exception?
The difference with Is there a way to prevent null values from being persisted while allowing others through?
My table can store rows with all the columns except the PK being nulls and that is by design because it allows creation of order then attaching an empty shipping/billing address to it to be filled later.
However I am creating a new end point that accepts order details(to be able to create order) which I validate. The shipping/billing address for such an order can be empty and such an order can be created, but this time the requirement is not to create empty shipping/billing addresses and I want to reuse the current code(which does not assumes that shipping/billing addresses can be empty) and only prevent the address from being saved when all its fields are empty.
Let me try to explain my problem with another approach. If all my Address entities can be created ONLY by calling AddressFacade.createOrUpdate(address)
I will be fine putting the null/empty checks as part of that method. However if cascading operation creates/updates "empty" Address row I have no way to prevent the action without setting the null constrains in the DB.