【问题标题】:Java Hibernate validation return invalid fieldsJava Hibernate 验证返回无效字段
【发布时间】:2015-12-17 15:39:54
【问题描述】:

我在我的项目中使用来自 Java Hibernate 的验证注解。我想验证收到的数据并返回一组无效字段。这可能吗?

假设我有一个名为 Car 的 Java 类:

public class Car {

    @NotNull
    private String manufacturer;

    @NotNull
    @Size(min = 2, max = 14)
    @CheckCase(CaseMode.UPPER)
    private String licensePlate;

    @Min(2)
    private int seatCount;

    public Car ( String manufacturer, String licencePlate, int seatCount ) {
        this.manufacturer = manufacturer;
        this.licensePlate = licencePlate;
        this.seatCount = seatCount;
    }

    //getters and setters ...
}

假设我创建了一辆新车:

Car c = new Car("AUDI", NULL, 1);

这应该是不可能的,因为要填写车牌,座位数应该大于等于2。所以我想返回一个由两个元素组成的数组,说车牌和座位数无效(如有可能,附上额外信息)。

【问题讨论】:

  • 您是否无法在您的 Car 初始化函数中添加代码来测试和处理这些情况?
  • 也许问题不清楚。我想验证我创建的汽车并返回一个无效字段数组

标签: java hibernate validation


【解决方案1】:

正如ElmerCat 指出的那样,您的构造函数应定义为:

public Car (
  @NotNull String manufacturer,
  @NotNull @Size(min = 2, max = 14) @CheckCase(CaseMode.UPPER) String licensePlate,
  @Min(2) int seatCount) {
    this.manufacturer = manufacturer;
    this.licensePlate = licensePlate;
    this.seatCount = seatCount;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-03
    • 2019-10-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多