据我了解,当杰克逊解组一个对象时,请求调用中未提及的字段将设置为默认值(如果是对象,则为 null),并且如果对该特定字段有约束,例如 @NotNull,则验证失败. 因此无法进行部分更新。
有谁知道最好的解决方法是什么(REST 中的部分更新)?以前有没有人实施过这样的事情?
我的直觉是,必须合并原始对象(来自 db)和新的未编组对象,然后该对象应该得到验证,但真的不知道如何实现这一点。任何其他想法将不胜感激。
我正在使用 Spring 3.1.2 和 Jackson 1.9.7。
据我了解,当杰克逊解组一个对象时,请求调用中未提及的字段将设置为默认值(如果是对象,则为 null),并且如果对该特定字段有约束,例如 @NotNull,则验证失败. 因此无法进行部分更新。
有谁知道最好的解决方法是什么(REST 中的部分更新)?以前有没有人实施过这样的事情?
我的直觉是,必须合并原始对象(来自 db)和新的未编组对象,然后该对象应该得到验证,但真的不知道如何实现这一点。任何其他想法将不胜感激。
我正在使用 Spring 3.1.2 和 Jackson 1.9.7。
您可以使用自省将自己的未编组对象与数据库中的现有对象合并。
import java.beans.Introspector;
...
Class<?> entityClass = YourEntity.class
// oldEntity is from database
oldEntity = entityManager.getReference(entityclass, id);
for (PropertyDescriptor property : Introspector.getBeanInfo(entityClass).getPropertyDescriptors()) {
if (property.getReadMethod() != null && property.getWriteMethod() != null) {
// You retrieve the value of the current property of your unmarshalled entity
Object newValue = property.getReadMethod().invoke(unmarshalledEntity);
if (value != null) {
property.getWriteMethod().invoke(oldEntity, newValue);
}
}
}
但是使用此解决方案,您无法将字段更新为null
......这可能是一个问题。这只是一个想法,您应该注意 的类型value
,它可能是另一个 bean,因此您必须递归地自省您的数据。