简体   繁体   中英

JPA Check if entity can be deleted

How can I check if entity in JPA can be deleted and data integrity exception won't be thrown? Only way that came to my mind is to check all referenced entities one by one or try to delete in transaction and then rollback but is there some other simpler way?

If by "can be deleted" you mean "if entity exists in persistence context", you already answered your question:

try to delete in transaction and then rollback

If something went wrong during transaction then rollback

Well I use this approach...

public void doDelete() {        
    try {
        deleteData();           
    } catch (RuntimeException runtimeException) {
        if (getRootThrowable(runtimeException).getMessage().contains("violates foreign key constraint")) {
            //can't delete entity
        }               
    }
}

public static Throwable getRootThrowable(Throwable t) {
    Throwable result = t;

    while (result.getCause() != null) {
        result = result.getCause();
    }

    return result;
}

I'm not that fan of this, but it does the job for me...

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