Hibernate ScriptAssert用于数组验证

我正在使用Hibernate Script Assert进行条件验证: 如果commRolesId包含4并且gnrlTransportersId数组列表为空,我想显示错误消息。

@ScriptAssert(lang="javascript",script="this.commRolesId.indexOf(4) >= 0 && _this.gnrlTransportersId.length == 0",message="{notBlank.message}")
public class CommUserDto {
    @Size(min = 1,message = "{notBlank.message}")
    private List<Long> commRolesId = new ArrayList<>();

    private List<Long> gnrlTransportersId = new ArrayList<>();
}

但是,即使commRolesId数组不包含4,它也会抛出该消息。

请帮助。谢谢。

kingkong1900 回答:Hibernate ScriptAssert用于数组验证

编辑:

import java.util.ArrayList;
import java.util.List;

import javax.validation.constraints.Size;

import org.hibernate.validator.constraints.ScriptAssert;

@ScriptAssert(
    lang = "javascript",script = "!(_this.commRolesId.contains(4) && _this.gnrlTransportersId.isEmpty())",message = "errorMessage")
public class CommUserDto {
  @Size(min = 1,message = "should not be empty")
  private List<Long> commRolesId = new ArrayList<>();

  private List<Long> gnrlTransportersId = new ArrayList<>();

  public List<Long> getCommRolesId() {
    return commRolesId;
  }

  public void setCommRolesId(List<Long> commRolesId) {
    this.commRolesId = commRolesId;
  }

  public List<Long> getGnrlTransportersId() {
    return gnrlTransportersId;
  }

  public void setGnrlTransportersId(List<Long> gnrlTransportersId) {
    this.gnrlTransportersId = gnrlTransportersId;
  }
}

测试:

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;

public class Test {

  public static void main(String[] args) {
    CommUserDto dto = new CommUserDto();
    List<Long> commRolesId = new ArrayList<>();
    commRolesId.add(1L);
    List<Long> gnrlTransportersId = new ArrayList<>();
    dto.setGnrlTransportersId(gnrlTransportersId);
    dto.setCommRolesId(commRolesId);
    Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
    Set<ConstraintViolation<CommUserDto>> constraintViolations = validator.validate(dto);
    System.out.println(constraintViolations.size());
    System.out.println(constraintViolations);
  }
}
本文链接:https://www.f2er.com/3101685.html

大家都在问