Reputation: 6868
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?
Upvotes: 2
Views: 1888
Reputation: 10058
Well I use this approach...
public void doDelete() {
try {
deleteData();
} catch (RuntimeException runtimeException) {
if (getRootThrowable(runtimeException).getMessage().contains("Referential integrity constraint violation")) {
//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...
Upvotes: 1
Reputation: 19026
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
Upvotes: 3