工作中遇到的问题--使用注解进行增加删除修改的验证
自定義驗證的注解:
/**
?* 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"/>即可。
轉載于:https://www.cnblogs.com/ly-radiata/p/4792631.html
總結
以上是生活随笔為你收集整理的工作中遇到的问题--使用注解进行增加删除修改的验证的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ASP.NET工作笔记之一:图片上传预览
- 下一篇: TypeScript - Interfa