zoukankan      html  css  js  c++  java
  • 工作中遇到的问题--使用注解进行增加删除修改的验证

    自定义验证的注解:

    /**
     * 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"/>即可。

  • 相关阅读:
    一、介绍与基础操作命令
    ES配置详细说明
    通过命令名称查询进程id
    应用商店流程
    你对女人好并不会让她爱上你
    java 对list进行排序
    java web判断是否登录
    支付返回post请求数据
    不方便的事情,人们都不大会去做
    不方便的事情,人们都不大会去做
  • 原文地址:https://www.cnblogs.com/ly-radiata/p/4792631.html
Copyright © 2011-2022 走看看