Java Spring3.1和Jackson:在验证之前合并数据库实体和未经授权的参数
据我所知,当Jackson对某个对象进行解组时,请求调用中未提及的字段将设置为默认值(如果是对象,则为null),如果该特定字段上存在约束,例如@NotNull,则验证失败。因此,不可能进行部分更新 有人知道这方面的最佳解决方法(REST中的部分更新)是什么吗?以前有人实施过这样的事情吗 我的预感是,必须合并原始对象(来自db)和新的未编组对象,然后该对象应该得到验证,但实际上不知道如何实现。如有其他想法,将不胜感激Java Spring3.1和Jackson:在验证之前合并数据库实体和未经授权的参数,java,spring-mvc,jackson,spring-3,Java,Spring Mvc,Jackson,Spring 3,据我所知,当Jackson对某个对象进行解组时,请求调用中未提及的字段将设置为默认值(如果是对象,则为null),如果该特定字段上存在约束,例如@NotNull,则验证失败。因此,不可能进行部分更新 有人知道这方面的最佳解决方法(REST中的部分更新)是什么吗?以前有人实施过这样的事情吗 我的预感是,必须合并原始对象(来自db)和新的未编组对象,然后该对象应该得到验证,但实际上不知道如何实现。如有其他想法,将不胜感激 我使用的是Spring 3.1.2和Jackson 1.9.7。您可以使用自省
我使用的是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);
}
}
}
import java.beans.Introspector;
...
Class entityClass=YourEntity.Class
//oldEntity来自数据库
oldEntity=entityManager.getReference(entityclass,id);
for(PropertyDescriptor属性:Introspector.getBeanInfo(entityClass.getPropertyDescriptors()){
if(property.getReadMethod()!=null&&property.getWriteMethod()!=null){
//您可以检索取消编组实体的当前属性的值
Object newValue=property.getReadMethod().invoke(unmarshalledEntity);
if(值!=null){
property.getWriteMethod().invoke(oldEntity,newValue);
}
}
}
但使用此解决方案,您无法将字段更新为null
。。。这可能是个问题。
这只是一个想法,您应该注意
值的类型,它可能是另一个bean,因此您必须递归地反思您的数据。是否可以使用Jackson和@Valid annotation将其结合起来?意思是,在解组newEntity对象之前或之后从数据库中获取原始对象,然后验证合并对象?这并不能完全回答我的问题,但对于合并部分,你是对的!