PersistenceException:无法删除或更新父行:外键约束失败

时间:2015-12-01 18:19:14

标签: java playframework ebean

我的代码中存在问题,这是有效但非常有效 丑陋且容易出错,我正在检查基于错误的条件 在异常消息上,所以我需要一个改变的建议 这个。 我有一个实体A和一个实体B有一个B(标识符) 引用为“外键”,所以如果找到一个B那个引用 A和我尝试删除A操作失败并启动 “的PersistenceException”。

注意:

1 - 我对级联中的删除不感兴趣。

2 - 我对前置条件保证不感兴趣(检查在删除A之前没有找到引用A的B)。

3 - 我的目标是尝试删除A,如果失败则处理异常,但是 用枚举,错误类型或其他选项替换pe.toString().contains("...")(如果可能的话)。

先谢谢,这是我的代码:

public static Result delete() {
        JsonNode json = request().body().asJson();        
        try {
            Long id = json.get("id").asLong();
            models.EntityA entity = models.EntityA.findByPropertie("id", id);
            models.EntityA.delete(entity);
            return ok();
        } catch(PersistenceException pe) {
            if (pe.toString().contains("Cannot delete or update a parent row: a foreign key constraint fails")) {
                appLogger.error(Messages.get("EntityA.delete.ForeignKeyConstraint"), pe);
                return internalServerError("ForeignKeyConstraint");   
            } else {
                appLogger.error(Messages.get("EntityA.delete.unexpectedError"), pe);
                return internalServerError("unexpectedError");
            }
        } catch (Exception e) {
            .
            .
            .
        }
    }

0 个答案:

没有答案