简体   繁体   中英

JPA EntityManager not throwing Constraint Violation on delete

For my project i have to allow the User to delete some Database entries. But in my case it should fail now, because there a some restrictions in Database. I can't show the Database DDL, because i am not allowed to.

The problem is that the code is not throwing any error, so the outcome is a message which says that the item was deleted. But of course it will fail, because a constraint violation.

So in the moment i will give the User a positive feedback for this action, but it should be a negative. The item is still in Database, this will confuse the User later on, if the item is not deleted. If there is no constraint violation, the entity will be deleted.

My code to remove entities looks like this, T is is defined in extending classes, to not replicate code.

Thanks in advance!

public void delete(final T item) throws DAOException {
    EntityManager entityManager = EntityManagerFactoryCentral.getEntityManager();
    EntityTransaction transaction = entityManager.getTransaction();
    try {
        transaction.begin();
        entityManager.remove(entityManager.contains(item) ? item : entityManager.merge(item));
        transaction.commit();
    } catch (Exception ex) {
        ex.printStackTrace();
        try {
            transaction.rollback();
        } catch (Exception rollbackEx) {
            logDatabaseError(rollbackEx);
        }

        logDatabaseError(ex);
        throw new DAOException(ex.getMessage(), ex);
    } finally {
        entityManager.close();
    }

    logTransactionSuccess(item, REMOVED_FROM);
}

Please replace your remove line with this one:

entityManager.remove(entityManager.getReference(item.getClass(), item.getPk()));

where PK is your primary key in that entity (not sure it's that simple since you have generics).

That merge IMO doesn't make much sense since you delete the entity.

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