简体   繁体   English

JPA EntityManager不会在删除时抛出违反约束的情况

[英]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. 我不能显示数据库DDL,因为不允许这样做。

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. 我删除实体的代码如下所示,T是在扩展类中定义的,以不复制代码。

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). 其中PK是您在该实体中的主键(由于拥有泛型,因此不确定它是否那么简单)。

That merge IMO doesn't make much sense since you delete the entity. 由于您删除了该实体,因此合并IMO没有多大意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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