如何在春季数据休息中有条件地应用验证组?
我有一个 spring data rest rest 带有基于属性的实体验证的实体类型的project 实体。我想使用当该属性设置为特定值时。
作为具体的示例,以以下实体类:
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.validation.constraints.NotNull;
@Entity
public class Animal {
public enum Type { FLYING, OTHER }
/**
* Validation group.
*/
public interface Flying {}
@Id
@GeneratedValue
private Integer id;
private Type type;
@NotNull(groups = Flying.class)
private Integer airSpeedVelocity;
@NotNull
private Integer weight;
public Integer getId() { return id; }
public void setId(Integer id) { this.id = id; }
public Type getType() { return type; }
public void setType(Type type) { this.type = type; }
public Integer getAirSpeedVelocity() { return airSpeedVelocity; }
public void setAirSpeedVelocity(Integer airSpeedVelocity) { this.airSpeedVelocity = airSpeedVelocity; }
public Integer getWeight() { return weight; }
public void setWeight(Integer weight) { this.weight = weight;}
}
当保存 Animal
type 飞行时,我想验证 airspeedvelocity
是非null 。保存其他动物时,我不希望这种验证。
目前,我有验证允许在保存之前检查验证,因此如果对象无效,则返回400不良请求错误:
@Bean
public ValidatingRepositoryEventListener preSaveValidator(
@Qualifier("defaultValidator") SmartValidator validator,
ObjectFactory<PersistentEntities> persistentEntitiesFactory) {
ValidatingRepositoryEventListener eventListener =
new ValidatingRepositoryEventListener(persistentEntitiesFactory);
eventListener.addValidator("beforeCreate", validator);
eventListener.addValidator("beforeSave", validator);
return eventListener;
}
}
请求:
{ "type": "FLYING" }
当前400错误响应:
{
"errors": [
{
"entity": "Animal",
"property": "weight",
"invalidValue": null,
"message": "must not be null"
}
]
}
所需的400错误响应:
{
"errors": [
{
"entity": "Animal",
"property": "airSpeedVelocity",
"invalidValue": null,
"message": "must not be null"
},
{
"entity": "Animal",
"property": "weight",
"invalidValue": null,
"message": "must not be null"
}
]
}
我如何执行此条件验证,应用程序应用程序飞行
验证组当请求实体为动物
其中 type == flage
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一种解决方案是使用自定义的
验证器
自动检查输入类型,必要时自动应用自定义验证组:请注意,这还添加了
默认
验证组,因为否则也不会执行标准验证。One solution is to use a customized
Validator
that automatically checks the input type, automatically applying the custom validation groups if necessary:Note that this also adds the
Default
validation group, since otherwise the standard validations would not also be performed.Hibernate验证 可用于根据对象状态动态定义默认验证组。
per
在这种情况下,可以创建
defaultGroupSequenceProvider
,该使用flying
group(加上标准默认组)时,当对象的type> type
属性是飞行,否则标准默认组。
A Hibernate Validation
DefaultGroupSequenceProvider
can be used to dynamically define the default validation group based on the state of the object.Per the reference guide:
In this case, a
DefaultGroupSequenceProvider
can be created which uses theFlying
group (plus the standard default group) when the object'stype
property isFLYING
, and the standard default group otherwise.