本文介绍了JPA实体验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我正在尝试在Java EE容器中设置应用程序。我使用JPA进行持久化,并且还使用 javax.validation.constraints。* 约束。默认情况下,容器在 @PrePersist @PreUpdate 生命周期事件期间验证实体,这对我有好处,但是如何处理 ConstraintViolationException

Ok, I'm trying to setup an application in a Java EE Container. I use JPA for persistence and I also use the javax.validation.constraints.* constraints. By default the container validate the entities during the @PrePersist and @PreUpdate lifecycle events and it's good for me, but how do I handle the ConstraintViolationException?

我找不到任何文档,欢迎提出任何建议。

I can't find any docs on it, any suggestion is welcomed.

推荐答案

嗯,你可以抓住它:)这是一个例子(来自单元测试):

Well, you could catch it :) Here is an example (from a unit test):

public class CustomerTest {
    private static EntityManagerFactory emf;
    private EntityManager em;

    @BeforeClass
    public static void createEntityManagerFactory() {
        emf = Persistence.createEntityManagerFactory("MyPu");
    }

    @AfterClass
    public static void closeEntityManagerFactory() {
        emf.close();
    }

    @Before
    public void beginTransaction() {
        em = emf.createEntityManager();
        em.getTransaction().begin();
    }

    @After
    public void rollbackTransaction() {
        if (em.getTransaction().isActive()) {
            em.getTransaction().rollback();
        }
        if (em.isOpen()) {
            em.close();
        }
    }

    @Test
    public void nameTooShort() {
        try {
            Customer customer = new Customer("Bo");
            em.persist(customer);
            em.flush();
            fail("Expected ConstraintViolationException wasn't thrown.");
        } catch (ConstraintViolationException e) {
            assertEquals(1, e.getConstraintViolations().size());
            ConstraintViolation<?> violation = e.getConstraintViolations().iterator().next();

            assertEquals("name", violation.getPropertyPath().toString());
            assertEquals(Size.class, violation.getConstraintDescriptor().getAnnotation().annotationType());
        }
    }
}

我的客户看起来像:

@Entity
public class Customer {
    @Id @GeneratedValue
    @NotNull
    private Long id;

    @NotNull
    @Size(min = 3, max = 80)
    private String name;

    private boolean archived;

    ...
}

但这只是一个示例显示API的一小部分。

But this was just an example to show a tiny part of the API.

在我看来,你应该在视图级别实际处理验证。许多演示框架支持Bean验证:JSF 2.0,Wicket,Spring MVC ...

In my opinion, you should actually handle the validation at the view level. Many presentation frameworks support Bean Validation: JSF 2.0, Wicket, Spring MVC...






  • 6.3. Presentation layer validation
  • Spring MVC, Spring Bean Validation Framework and validating confirm password / confirm email fields.
  • Wicket JSR-303 Validators
  • TOTD #123: f:ajax, Bean Validation for JSF, CDI for JSF and JPA 2.0 Criteria API

这篇关于JPA实体验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 01:20