キーは、行データが特定の基準に基づいて一意であるかどうかを検証できる独自の検証アノテーションを作成することです。
は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;
私はあなたがあなた自身の検証アノテーションを記述する必要が怖いです。 –
チップをありがとう、私はこの1つを理解しようとするつもりです:https://docs.jboss.org/hibernate/validator/5.0/reference/en-US/html/validator-customconstraints.html#validator-customconstraints –