简体   繁体   English

关于Hibernate bean验证

[英]About Hibernate bean validation

I've added hibernate validator to my project, and annotated my class with the relevant constraints.我已将 hibernate 验证器添加到我的项目中,并使用相关约束对我的 class 进行了注释。 This is my pom.xml:这是我的 pom.xml:

<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-hibernate-orm-panache</artifactId>
</dependency>
<dependency>
    <groupId>io.quarkus</groupId>
    <artifactId>quarkus-hibernate-validator</artifactId>
</dependency>

and this is the annotated class:这是带注释的 class:

public class EmployeeProject extends PanacheEntity {

    @NotNull
    @ManyToOne
    private Employee employee;

    @NotNull
    @ManyToOne
    private Project project;

    @Column
    @Min(value = 1)
    private int quantity;

}

When I try to persist a not valid bean - null employee/project and/or non-positive quantity - through Java code, a validation exception is raised, as expected.当我尝试通过 Java 代码保留无效的 bean - null 员工/项目和/或非正数时,会引发验证异常,如预期的那样。

However, when I try to persist a not valid tuple directly into the database, surprisingly no exceptions or DB errors are raised.但是,当我尝试将无效元组直接保存到数据库中时,令人惊讶的是没有引发异常或数据库错误。 Indeed the reason is that the employee_project auto-generated by Hibernate have no validation constraints - just the two foreign keys constraints.实际上原因是 Hibernate 自动生成的employee_project没有验证约束——只有两个外键约束。 I know there is no simple way to translate @Min in SQL, but boy I was at least expecting a NOT NULL on employee_id and project_id !我知道没有简单的方法可以在 SQL 中翻译@Min ,但男孩我至少期望在employee_idproject_id上出现 NOT NULL!

Is this the regular behavior, or am I missing something?这是常规行为,还是我错过了什么?

This is explained in the @Min javadoc :这在@Min javadoc中有解释:

null elements are considered valid.

A null value is an undefined values, with @Min you are saying that, if the value is defined, it must be at least something. null值是未定义的值, @Min你是说,如果值已定义,它必须至少是一些东西。

The other constraints are missing because @ManyToOne default value is optional=true and the JPA annotation has precedence over the Bean Validation one when it comes to the creation of the DB.缺少其他约束,因为@ManyToOne默认值为optional=true并且 JPA 注释在创建数据库时优先于 Bean Validation 注释。

It makes sense because somebody might want to validate columns on the database that are without constraints.这是有道理的,因为有人可能想要验证数据库上没有约束的列。

It will work if you use @ManyToOne(optional=false) .如果您使用@ManyToOne(optional=false) ,它将起作用。

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

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