关键是创建您自己的验证注释,能够根据特定条件验证行数据是否唯一。
让服务iterface延长UniqueValidated
和落实执行验证
public interface UniqueValidated {
boolean isUnique(Object value, String fieldName) throws UnsupportedOperationException;
}
public interface FooService extends UniqueValidated {
// add, delete...
}
public class FooServiceImpl implements FooService {
// add, delete...
@Override
public boolean isUnique(Object value, String fieldName)
throws UnsupportedOperationException {
// the logic of validation itself, feel free to use DAO implementations
}
}
创建你把在映射属性注释的方法。
@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE
})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = UniqueValidator.class)
@Documented
public @interface Unique {
String message() default "{validation.unique}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
Class<? extends UniqueValidated> service();
String serviceQualifier() default "";
String fieldName();
}
最后创建带注释的类处理。
public class UniqueValidator implements ConstraintValidator<Unique, Object> {
@Autowired
private ApplicationContext applicationContext;
private UniqueValidated service;
private String fieldName;
@Override
public void initialize(Unique unique) {
Class<? extends UniqueValidated> clazz = unique.service();
this.fieldName = unique.fieldName();
this.service = this.applicationContext.getBean(clazz);
}
@Override
public boolean isValid(Object o, ConstraintValidatorContext constraintValidatorContext) {
if (this.service == null || this.service.isUnique(o, this.fieldName)) {
constraintValidatorContext.disableDefaultConstraintViolation();
return true;
}
return false;
}
}
我从JBoss Docs的在线教程中获得启发。这是相当复杂的结构,但它很好地导致了结果。最大的优势无疑是您可以通过任何实施UniqueValidated
的服务对自定义进行独特验证。无论如何,你需要上面这些片段为你的项目定制。
映射很简单:
@Unique(service = FooService.class, fieldName = "theNameOfThisField"
@Column(name = "...")
private String theNameOfThisField;
恐怕你必须写自己的验证注释。 –
感谢您的提示,我会试着理解这一个:https://docs.jboss.org/hibernate/validator/5.0/reference/en-US/html/validator-customconstraints.html#validator-customconstraints –