gpt4 book ai didi

spring - 按逻辑顺序进行 JSR-303 验证

转载 作者:行者123 更新时间:2023-12-02 06:58:41 24 4
gpt4 key购买 nike

我的域模型类验证约束中有这样的字段:

@Column(nullable = false, name = "name")
@NotEmpty(groups = {Envelope.Insert.class, Envelope.Update.class})
@Size(min = 3, max = 32)
private String name;

当此字段为空 ("") 或 null 时,验证器会生成“不能为空”和“大小必须介于...”错误消息。我理解它,但是当我向客户端显示此验证错误时,这似乎很奇怪(因为当某些内容为空/空时,它无法满足大小要求,这不符合逻辑)。

有什么方法可以告诉 Spring 按正确的顺序进行验证吗?如果不是@NotEmpty,则不检查@Size,当满足@NotEmpty时,检查@Size

最佳答案

根据Hibernate official document:

By default, constraints are evaluated in no particular order and this regardless of which groups they belong to. In some situations, however, it is useful to control the order of the constraints evaluation. In order to implement such an order one would define a new interface and annotate it with @GroupSequence defining the order in which the groups have to be validated.

首先,创建两个接口(interface) FirstOrder.class 和 SecondOrder.class,然后使用 @GroupSequence 注解在 OrderedChecks.java 中定义一个组序列。

public interface FirstOrder {
}

public interface SecondOrder {
}

@GroupSequence({FirstOrder.class, SecondOrder.class})
public interface OrderedChecks {
}

最后,在 Bean 约束注释中添加组。

@Column(nullable = false, name = "name")
@NotEmpty(groups = {FirstOrder.class, Envelope.Insert.class, Envelope.Update.class})
@Size(min = 3, max = 32, groups=SecondOrder.class)
private String name;

关于spring - 按逻辑顺序进行 JSR-303 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42447159/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com