【问题标题】:How to handle ConstraintViolationException in hibernate如何在休眠中处理 ConstraintViolationException
【发布时间】:2013-08-22 13:04:34
【问题描述】:

我正在尝试 ConstraintViolationException,我创建了一个简单的约束电子邮件并为其实现了验证器:

EmailValidator implements ConstraintValidator<Email, String> { }

我的问题是当我从 entityManager 调用persist 时,它没有捕获异常。我查看了 ConstraintViolationException,发现祖先类是 RuntimeException,所以它没有被选中,但我很困惑,因为我看到很多文章都捕获了相同的异常。

任何人有任何意见和解决方法?

【问题讨论】:

  • 为什么您认为您无法捕获运行时异常?你可以。实体经理不会为您捕获它。约束的全部意义在于抛出异常,如果它被违反了。
  • 是的,我忘了我需要手动刷新它,这不是一个好主意。可能必须使用自定义验证器来解决。或者您对此有什么解决方案或解决方法?
  • 我不明白你在问什么。你必须冲洗什么,做什么?您要解决的问题是什么?你想达到什么目标?

标签: hibernate java-ee-6


【解决方案1】:

这个链接解决了我的问题:Catch PersistenceException or ConstraintViolationException in JBoss AS 7

然后,作为一种解决方法,我创建了一个电子邮件验证器并将一个 f:validator 添加到我正在验证的字段中。

@FacesValidator("emailValidator")
public class EmailValidator implements Validator {

public void validate(FacesContext context, UIComponent component,
        Object value) throws ValidatorException {

    ResourceBundle resourceBundle = ResourceBundle.getBundle("messages",
            Locale.ENGLISH);

    if (StringUtils.isBlank(value)) {
        return;
    } else {
        try {
            InternetAddress emailAddr = new InternetAddress(
                    value.toString());
            emailAddr.validate();
        } catch (AddressException ex) {
            FacesMessage facesMessage = new FacesMessage();
            String message = resourceBundle
                    .getString("message.error.invalidEmail");
            message = MessageFormat.format(message,
                    getLabel(context, component));
            facesMessage.setDetail(message);
            facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR);

            throw new ValidatorException(facesMessage);
        }
    }

}

将此添加到您正在验证的字段中。

<f:validator for="#{cc.attrs.id}_text" validatorId="emailValidator"></f:validator>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-24
    • 1970-01-01
    • 1970-01-01
    • 2011-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多