hibernate 正在验证无法通过添加新注解进行修改的类

kcugc4gi  于 2023-10-23  发布在  其他
关注(0)|答案(1)|浏览(100)

该模型由一些工具生成。特定字段由例如@NotNull注解来注解。我不能修改生成的类。我需要对生成的类进行额外的验证,比如检查字符串字段的值不包含空字符串,然后抛出ConstraintViolationException。目前,我遍历类以查找String字段类型,然后在空字符串的情况下,我需要实现自己的ConstraintViolation接口,这非常困难。看起来像这样:

Validator validator = Validation.buildDefaultValidatorFactory()
            .getValidator();
    Set< ConstraintViolation< E > > validationErrors = validator.validate(aEntity);
    Field[] fields = aEntity.getClass().getDeclaredFields();
    for (Field f : fields) {
        Class<?> type = f.getType();
        if (type == String.class) {
            try {
                String v = (String) f.get(aEntity);
                // check that value is not an empty string
                if (v == null || !v.trim().isEmpty()) {
                    validationErrors.add(new ConstraintViolation<E>() {
                        @Override
                        public String getMessage() {
                            return null;
                        }

                        @Override
                        public String getMessageTemplate() {
                            return null;
                        }

                        @Override
                        public E getRootBean() {
                            return null;
                        }

                        @Override
                        public Class<E> getRootBeanClass() {
                            return null;
                        }

                        @Override
                        public Object getLeafBean() {
                            return null;
                        }

                        @Override
                        public Object[] getExecutableParameters() {
                            return new Object[0];
                        }

                        @Override
                        public Object getExecutableReturnValue() {
                            return null;
                        }

                        @Override
                        public Path getPropertyPath() {
                            return null;
                        }

                        @Override
                        public Object getInvalidValue() {
                            return null;
                        }

                        @Override
                        public ConstraintDescriptor<?> getConstraintDescriptor() {
                            return null;
                        }

                        @Override
                        public <U> U unwrap(Class<U> type) {
                            return null;
                        }
                    });
                }
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
    }

有没有可能让这件事变得更简单?

tp5buhyn

tp5buhyn1#

对于无法编辑类以向其添加验证注解的情况,有两个选项:

通过XML解析约束

要使用这种方法,你需要添加一个META-INF/validation.xml,然后在里面你可以定义/重新定义你的约束:

<?xml version="1.0" encoding="UTF-8"?>
<constraint-mappings
    xmlns="https://jakarta.ee/xml/ns/validation/mapping"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
        https://jakarta.ee/xml/ns/validation/mapping
        https://jakarta.ee/xml/ns/validation/validation-mapping-3.0.xsd"
    version="3.0">

    <!-- note that you can use ignore-annotations 
        to either ignore any annotation constraints 
        or include them, depending on your needs -->
    <bean class="com.acme.common.model.SomeType" ignore-annotations="false">
       <field name="someField">
           <constraint annotation="jakarta.validation.constraints.NotBlank"/>
           [...]
       </field>
       [...]
    </bean>
</constraint-mappings>

要了解更多细节,请查看本规范的这一部分。

编程约束定义

或者,Hibernate Validator提供了一种以编程方式添加约束的方法:

HibernateValidatorConfiguration configuration = Validation
        .byProvider( HibernateValidator.class )
        .configure();

ConstraintMapping constraintMapping = configuration.createConstraintMapping();

constraintMapping
    .type( Car.class )
        .field( "manufacturer" )
            .constraint( new NotNullDef() )
        .field( "licensePlate" )
            .ignoreAnnotations( true )
            .constraint( new NotNullDef() )
            .constraint( new SizeDef().min( 2 ).max( 14 ) )
    .type( RentalCar.class )
        .getter( "rentalStation" )
            .constraint( new NotNullDef() );

Validator validator = configuration.addMapping( constraintMapping )
        .buildValidatorFactory()
        .getValidator();

有关更多详细信息,请查看Hibernate Validator文档的这一部分。
如果您不知道哪些字段将不需要应用空/空白约束,则可以尝试使用反射遍历字段,然后基于该信息通过编程API定义约束。一旦将约束添加到验证器中,您就应该能够只使用Validator#validate(..)

相关问题