gpt4 book ai didi

java - Hibernate validator 自定义约束取决于基类

转载 作者:行者123 更新时间:2023-12-01 10:07:10 26 4
gpt4 key购买 nike

我可以使用 Hibernate Validator (w/i Spring boot)创建自定义约束,其中验证取决于子类吗?示例:

public class Engine {
@NotEmpty
private String name;
@NotNull
private int power;
@NotNull // HERE I ONLY NEED VALIDATE IF THIS CLASS ARE ONE PROP FROM Car Class
private int color;

... getter and setter
}

Here I have 2 classes,

public class Car {
@NotEmpty
private String name;
@Valid
private Engine engine;
... getter and setter
}

public class Bike {
@NotEmpty
private String name;
@Valid
private Engine engine; // HERE I DONT NEED TO VALIDATE THE COLOR
... getter and setter
}

最佳答案

您应该能够使用 @ConvertGroup 执行您想要的操作:

组接口(interface):

public interface BasicEngineChecks {
}

public interface ExtendedEngineChecks {
}

更新的示例:

@GroupSequence({ BasicEngineChecks.class, ExtendedEngineChecks.class })
public class Engine {
@NotEmpty(groups = BasicEngineChecks.class)
private String name;

@NotNull(groups = BasicEngineChecks.class)
private int power;

@NotNull(groups = ExtendedEngineChecks.class)
private int color;

// ...
}

汽车没有什么特别的。级联验证将通过默认组,该组将转换为 BasicEngineChecks 以及 ExtendedEngineChecks

的所有约束
public class Car {
@NotEmpty
private String name;

@Valid
private Engine engine;

// ...
}

对于Bike,我们只进行显式转换,评估BasicEngineChecks:

public class Bike {
@NotEmpty
private String name;

@Valid
@ConvertGroup(from = Default.class, to = BasicEngineChecks.class)
private Engine engine;

// ...
}

关于java - Hibernate validator 自定义约束取决于基类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36366668/

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