關鍵是創建您自己的驗證註釋,能夠根據特定條件驗證行數據是否唯一。
讓服務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 –