我有一个像这样的用户类:
@Document(collection = "users")
public class User {
@Id
private String id;
String username;
String password;
String description;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public String toString() {
return "User[id=" + id + ", username=" + username + ", password=" + password + ", description"
+ description + "]";
}
}
我能够执行有限的更新。像:
Query searchQuery = new Query(Criteria.where("id").is("shashi"));
mongoDBClient.updateFirst(searchQuery, Update.update("password", "newpassword"), User.class);
现在,如果我想要更新username and description
类的其他字段(User
),我需要多次调用updateFirst
方法。
我想避免这种情况,并将整个对象传递给updateFirst
方法。类似的东西:
mongoDBClient.updateFirst(searchQuery, Update.update(userObject), User.class);
基本上,我想使用java POJO对象在一次调用中编辑所有/多个字段。我怎么能做到这一点?
答案 0 :(得分:0)
使用java POJO对象在一次调用中编辑/所有多个字段,可以如下所示完成
1)查询需要更新的文件 - >我们得到了java对象
2)在java对象中进行所有修改
3)保存对象
代码:
Query query = new Query();
query.addCriteria(Criteria.where("id").is("shashi"));
User user = mongoOperation.findOne(query, User.class);
//modify the user object with the properties need to be updated
//Modify password and other fields
user.setPassword("newpassword");
user.setDescription("new description");
user.setUsername("NewUserName");
//save the modified object
mongoOperation.save(user);