使用休眠验证器验证Java泛型Pojos? (5.0)

时间:2019-07-18 06:58:59

标签: java hibernate validation generics

是否有使用休眠验证器验证泛型类型的更简洁方法?

考虑以下JSON

{
    "type" : "",
    "body" : "",
    .
    .
    .
    other inherited fields
}

映射到如下定义的参数化类

class Message<T extends Identifiable> extends Indentifiable{

    private String type;

    private T body;

    .
    .
    .

}

基于类型,我需要使用相应的bean来验证主体实体。消息仅充当占位符。我正在使用休眠5.0。浏览了文档,并尝试编写似乎不适用于通用类型的自定义注释和验证器

public class MessageValidator implements ConstraintValidator<MessageValidate, Message<? extends Identifiable>> {

    private static final ObjectMapper mapper = new ObjectMapper();


    @Override
    public void initialize(MessageValidate arg0) {


    }

    @Override
    public boolean isValid(Message<?> message, ConstraintValidatorContext arg1) {
        LOGGER.debug("I have reched here");
        if (message.type.equalsIgnoreCase("_XXXXXX__")) {
            // Deciding and Validating embedded entity at run time
        } else if (message.type.equalsIgnoreCase("__ZXZZZZZZZ____")) {
            // Deciding and Validating embedded entity at run time
        }
        return false;
    }
}

@Target( { ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = MessageValidator.class)
@Documented
public @interface MessageValidate {

}

0 个答案:

没有答案