I'm using hibernate validator to validate objects.I create a custom annotation constraint on the Filed to check if the value of that field is unique in the it's table.for checking uniqueness, i need the entity class(entityClass) and field name (columnName) and now i declare them in annotation. is there a way to get the entity class and property name (which this annotation is declared on) in initialize() or isValid() function somehow by reflection? here is my code.
Unique Annotation:
@Target({FIELD, ANNOTATION_TYPE})
@Retention(RUNTIME)
@Constraint(validatedBy = UniqueValidator.class)
@Documented
public @interface Unique {
String message() default "{Ir.validation.constraints.Unique.message}";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
String columnName();
Class<?> entityClass();
@Target({ FIELD, METHOD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Documented
@interface List {
Unique[] value();
}
}
UniqueValidator
public class UniqueValidator implements ConstraintValidator<Unique, Object>{
private String columnName;
private Class<?> entityClass;
@Override
public void initialize(Unique uniqueAnnotation) {
columnName = uniqueAnnotation.columnName();
entityClass = uniqueAnnotation.entityClass();
}
@Override
public boolean isValid(Object value, ConstraintValidatorContext context) {
if (value == null) {
return true;
}
return !DAO.isExist(entityClass, columnName, value);
}
}
Unique Annotaion Usage: public class User extends BaseEntity{
@Unique(columnName = "username", entityClass = User.class, groups = SignupChecks.class)
@NotNull(groups = LoginChecks.class)
@Column(nullable = false, unique = true)
private String username;
Note: i have BaseEntity class(parent of all entity) and i use @exist annotation (opposite unique) on id in it.the real problem is that child entity class will be determined in runtime. so i can't declare it in annotation !!!
Aucun commentaire:
Enregistrer un commentaire