JPA 实体验证

s.s*_*ini 6 java validation orm jpa jakarta-ee

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

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

Pas*_*ent 4

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

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());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我的客户看起来像:

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

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

    private boolean archived;

    ...
}
Run Code Online (Sandbox Code Playgroud)

但这只是一个示例,展示了 API 的一小部分。

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

也可以看看