简体   繁体   中英

Prevent JPA Entity from being persisted

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.

What I understand from your problem statement is that you want to prevent error at runtime for not-null constraints and other foreign key constraints when essential columns of a given row you are inserting are null. Then simple solution I think is : Apply null/empty check on all those fields before entityManager.persist call which can cause error if you insert them null/empty in DB. This will prevent error and row won't be inserted in the table.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM