我有一些领域Hibernate的验证注解类(如@NotNull
和@Size(min = 4, max = 50)
,等...)如何以编程方式调用在Spring中使用@Valid参数在@RequestMethod方法上运行的相同验证器?
public class MyClass {
Long id;
@NotEmpty
@Size(min = 4, max = 50)
String machineName;
@NotEmpty
@Size(min = 4, max = 50)
String humanName;
// Getters, setters, etc…
}
我也有一个自定义的控制器,作为一个JSON API和JSON是解串器在调用API方法时创建MyClass对象。在我的自定义控制器我要创建该类型的新对象的方法:
@RequestMapping(method = RequestMethod.POST)
public long createMyObject(@RequestBody @Valid MyClass newObj) {
// Create the object in the database
return newObj.getId();
}
和更新现有对象
@RequestMapping(method = RequestMethod.PUT)
public void updateMyObject(@RequestBody MyClass updatedObj) {
MyClass existingObj = // Get existing obj from DB by updatedObj.getId();
// Do some secondary validation, such as making sure that a specific
// field remains unchanged compared to the existing instance
if (existingObj.getMachineName() != null &&
!existingObj.getMachineName().equals(updatedObj.getMachineName())) {
throw new CannotChangeMachineNameException();
}
else {
updatedObj.setMachineName(existingObj.getMachineName());
}
// [HERE IS WHERE I WANT THE MAGIC TO HAPPEN]
// Save updatedObj to the database
}
虽然我可以在createMyObject
使用@Valid
,我不能用其他方法它在updateMyObject
中,因为我们的API实现要求machineName保持不变 - 用户可以使用完全排除machineName的JSON对象调用API,或者使用与数据库中存在的值相同的值来填充它。*
在将更新的对象保存到数据库之前,我想调用具有@Valid注释将导致调用的相同验证程序。我怎样才能找到这个验证器并使用它?
我想你可以使用验证组。除'machineName'上的'@NotNull'(或比较新名称和新名称的自定义验证器)之外的所有验证都在默认组中,并让剩余的验证器位于'Update'组中。在'updateMyObject'方法中使用这两个组。见http://docs.jboss.org/hibernate/validator/5.0/reference/en-US/html/chapter-groups.html#d0e2595 –