自定义验证的注解:
/**
* This constraint is to be put on object level for which need to validate on the Product SKU.
* It calls {@link ValidProductSKUValidator} to perform validation.
*
* @author System-In-Montion
*
*/
@Constraint(validatedBy = {ValidProductSKUValidator.class})
//This constraint annotation can be used only on class.
@Target({ElementType.TYPE})
@Retention(value = RetentionPolicy.RUNTIME)
@Documented
public @interface ValidProductSKU {
/** The message to return when the instance of product SKU fails the validation.*/
String message() default "{product.validation.SKU}";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
自定义验证的类:
/**
* The product sku validator
*
* @author System-In-Motion
*
*/
@Component
public class ValidProductSKUValidator implements
ConstraintValidator<ValidProductSKU, Product> {
@Autowired
private ProductRepository productRepository;
@Autowired
private EventRepository<Event> eventRepository;
/**
* Nothing to be done for initialization
*/
@Override
public void initialize(ValidProductSKU constraintAnnotation) {
// TODO Auto-generated method stub
}
/**
* Perform validation on the {@link productSKU} via the instance for
* {@link ValidProductSKUValidator}
*/
@Override
public boolean isValid(Product product, ConstraintValidatorContext context) {
if(product.getId()==null){ //validate create
return productRepository.countBySku(product.getSku()) > 0?false:true;
}else if(eventRepository.countByProduct(product.getId()) > 0){ //validate delete
return false;
}else if(productRepository.countBySkuIsAndIdIsNot(product.getSku(), product.getId()) > 0){ //validate update
return false;
}
return true;
}
}
在product这个entity上添加注解@ValidProductSKU
经过这样的设置后,每次在增加,删除和修改时就能验证是否合法了。
另外:在实现过程中也遇到一个小问题,就是isValid中传递的product值始终为空,原因是在更新的form表单里没有隐藏携带id值,只需添加<input th:field="*{id}" type="hidden"/>即可。