我有一些領域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 –