自定义bean验证约束和persist()验证

时间:2017-07-21 16:05:57

标签: java spring hibernate jpa bean-validation

记住孩子!您应该检查变量是否为null;)。很抱歉这个问题有这么简单的解决方案。脑滞后是真实的! 如果有人知道如何在持久化(更新)之前配置persistence.xml以检查验证,请发表评论,这个问题我还没有解决。

我试图在hibernate中创建自定义验证注释。遗憾的是在测试期间(使用Validator和ValidatorFactory)我很遗憾,我不明白为什么:

javax.validation.ValidationException: HV000028: Unexpected exception during isValid call.

这是我的注释:

@Documented
@Constraint(validatedBy=PeselValidator.class)
@Target({ElementType.FIELD,ElementType.METHOD,ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyPesel {
    String message() default "{wrong.pesel.format}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}
public class PeselValidator implements ConstraintValidator<MyPesel,String>{

    @Override
    public boolean isValid(String arg0, ConstraintValidatorContext arg1) {
        IF(ARG0==NULL)
RETURN FALSE; //!!!!!!!!!!!!!!
        //arg0.matches("^\\d{4}[1-31]\\d{5}$")
        if(arg0.length()==11)  
            return true;
        else
            return false;
    }

}

这是我的作者代码:

@Entity
public class Author {
    @Id
    @GeneratedValue
    private int Id;

    @NotNull
    @Size(min=5,max=30)
    private String name;

    @NotNull
    @MyPesel
    private String pesel;

    @ManyToMany
    @JoinColumn(name="book_id")
    private Collection<Book> book= new ArrayList<>();

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPesel() {
        return pesel;
    }

    public void setPesel(String pesel) {
        this.pesel = pesel;
    }
}

并测试:

@Test
    public void goodBookBadAuthor() {
        Book book=new Book();
        book.setTitle("quite good title");
        book.getAuthor().add(new Author());
        Author author=new Author();
        author.setName("y");
        author.setPesel("abc");
        book.getAuthor().add(author);
        Validator validator=validatorFactory.getValidator();

        Set<ConstraintViolation<Book>> constraintViolations=validator.validate(book);

        assertEquals(2,constraintViolations.size());
    }

第二个问题是,即使我不使用@Pesel测试也没关系,但是当我想用entityManager(使用persist())向数据库添加内容时,hibernate不会检查ma验证。我读到需要更改验证模式。我改变了它,但它不起作用。我真的希望你们能帮助我。有我的persistence.xml。

<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
             http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
    version="2.1">

    <persistence-unit name="ormBook">
        <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <class>bean.Book</class>
        <class>bean.Author</class>
        <properties>
            <property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver" />

            <property name="javax.persistence.jdbc.url"
                value="jdbc:mysql://127.0.0.1:3307/db_hibernate_3?useSSL=true&amp;serverTimezone=UTC&amp;logger=Slf4JLogger&amp;profileSQL=true" />

            <property name="javax.persistence.jdbc.user" value="root" />

            <property name="javax.persistence.jdbc.password" value="jbjb123" />
                  <property name="javax.persistence.validation.mode" value="AUTO"/>
     <property name="javax.persistence.validation.group.pre-persist" value="javax.validation.groups.Default" />
       <property name="javax.persistence.validation.group.pre-update" value="javax.validation.groups.Default" />
       <property name="javax.persistence.validation.group.pre-remove" value=""/>       
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />


            <property name="hibernate.connection.isolation" value="2" />
            <property name="hibernate.hbm2ddl.auto" value="create" />
            <property name="hibernate.connection.pool_size" value="10" />
        </properties>
    </persistence-unit>

</persistence>

1 个答案:

答案 0 :(得分:1)

在这种情况下,我相信你可以使用@Pattern注释,我相信。

根据我的经验,编写自定义注释会使事情变得更复杂,而hibernate提供的验证对于您可能需要的一切都很有用。

其他所有内容都应该在上面的图层中处理。