validator 基於hibernate實現靈活驗證

註解實體類

@Data
public class OrderDemandDTO implements DtoConverter<OrderDemand> {

    private Integer id;

    @NotNull(message = "訂單ID不能爲空")
    private Integer orderId;

    private Integer destinationCity;
    private String destinationCityName;

    @NotNull(message = "預定城市不能爲空")
    private Integer bookingCity;
    private String bookingCityName;

    @NotNull(message = "出發城市不能爲空")
    private Integer tripCity;
    private String tripCityName;


    private Integer minTravelDay;//最小出遊天數

    private Integer maxTravelDay;//最大出遊天數

    @JsonFormat(pattern = "yyyy-MM-dd")
    private Date startTravelDate;//開始出遊日期

    @JsonFormat(pattern = "yyyy-MM-dd")
    private Date endTravelDate;//結束出遊日期

    private BigDecimal minProductPrice;//產品起價-最小价格

    private BigDecimal maxProductPrice;//產品起價-最大價格

    @EnumValid(enumClass = SingleRoomPlanEnum.class, message = "單房差方案有誤")
    private String singleRoomPlan;
    private String singleRoomPlanName;

    @Override
    public void covertEntity2Dto(OrderDemand orderDemand) {
        MyBeanUtils.copyProperties(orderDemand, this);
        if(StringUtils.isNotBlank(this.singleRoomPlan)) this.singleRoomPlanName = SingleRoomPlanEnum.valueOf(this.singleRoomPlan).getName();
    }

    @Override
    public void covertDto2Entity(OrderDemand orderDemand) {
        MyBeanUtils.copyProperties(this, orderDemand);
    }

校驗類

public class MyValidator {

    static ValidatorFactory vf = Validation.buildDefaultValidatorFactory();
    static Validator validator = vf.getValidator();

    /**
     * 使用Validator校驗註解
     * @param param
     */
    public static void checkParams(Object param){
        checkParams(param, Default.class);
    }

    /**
     * 分組校驗
     * @param param
     * @param groups
     */
    public static void checkParams(Object param, Class<?>... groups){
        Set<ConstraintViolation<Object>> set = validator.validate(param, groups);
        for (ConstraintViolation<Object> constraintViolation : set) {
            throw new MySystemException(SystemErrorEnum.BAD_REQUEST, constraintViolation.getMessage());
        }
    }
}

調用方法:

  MyValidator.checkParams(orderDemandDTO );
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章