请参阅以下课程
public class Parent {
private String name;
private int age;
private Date birthDate;
// getters and setters
}
Run Code Online (Sandbox Code Playgroud)
假设我已经创建了一个父对象,如下所示
Parent parent = new Parent();
parent.setName("A meaningful name");
parent.setAge(20);
Run Code Online (Sandbox Code Playgroud)
请注意,根据上面的代码,birthDate属性为null.现在我想从父对象复制到另一个非空属性.就像是
SomeHelper.copyNonNullProperties(parent, anotherParent);
Run Code Online (Sandbox Code Playgroud)
我需要它,因为我想更新anotherParent对象而不用空值覆盖其非null.
你知道这样的帮手吗?
我接受最少的代码作为答案是否没有帮助
问候,
Spring BeanUtils.copyProperties()提供了在复制bean时忽略特定属性的选项:
public static void copyProperties(Object source,
Object target,
String[] ignoreProperties) throws BeansException
Run Code Online (Sandbox Code Playgroud)
Apache Commons BeanUtils是否提供类似的功能?
使用Spring时也可以忽略空值BeanUtils.copyProperties(),我在Commons BeanUtils中看到这个功能:
Date defaultValue = null;
DateConverter converter = new DateConverter(defaultValue);
ConvertUtils.register(converter, Date.class);
Run Code Online (Sandbox Code Playgroud)
我可以用Spring的BeanUtils实现同样的目标吗?
在我的数据库中,我有一个看起来像这样的文档
{
"_id" : ObjectId("5864ddd8e38112fd70b89893"),
"_class" : "com.apic.models.UserReg",
"name" : "Bijay",
"email" : "apic.apps@gmail.com",
"psd" : "16d932a5a3da90cc6afd831016b5a6821f0badf7e2c624159205924433613c3a",
"activationToken" : "fe8376ea2dbdf61ebc0f11a2361d741ba3178362d5bf876cf47e6a126bc5b39c",
"verified" : false
}
Run Code Online (Sandbox Code Playgroud)
我也有一个看起来像这样的豆子
public class User {
@Id
private int id;
private String name;
private String email;
// getter/setter methods
}
Run Code Online (Sandbox Code Playgroud)
因此,当我尝试调用save()方法时MongoOperations,它会替换所有缺少的属性,如psd,verified和activationToken.
mongoOperations.save(user, COLLECTION);
Run Code Online (Sandbox Code Playgroud)
有什么方法可以更新我的模型类中的现有属性并保留其他属性吗?