我的应用程序当用户尝试注册他从表单输入的数据时,将其保存到两个不同的文档中
public Result schoolSignUp(FormSchoolSignUp signUpForm){
User userEntered=null;
if(signUpForm.getEmail()!=null){
User user=this.userService.getUser(signUpForm.getEmail());
// user null means there is no user in data base
if(user==null){
List<String> roles=new ArrayList<>();
roles.add("ROLE_SCHOOL");
// data is assigned to user
this.user.setUserName(signUpForm.getEmail());
this.user.setPassword(signUpForm.getPassword());
this.user.setRoles(roles);
//user collection data is stored in the data base
userEntered=this.userService.saveUser(this.user); // first
write operation
}
else{
this.result.setResult(false);
this.result.setMessage("User Already Exist");
}
}
else{
this.result.setResult(false);
this.result.setMessage("User Name is not entered");
}
if(userEntered!=null){
// data is assigned to school
this.school.setName(signUpForm.getName());
this.school.setUserId(signUpForm.getEmail());
this.school.setUserId(userEntered.getUserName());
this.school.setAddress(signUpForm.getAddress());
this.school.setState(signUpForm.getState());
this.school.setCity(signUpForm.getCity());
//school collection is stored in the data base
this.schoolRepository.insert(this.school);//second write
operation
this.result.setResult(true);
this.result.setMessage("Success");
}
return this.result;
}
我的问题是,如果在第一次写入和第二次写入之间出现问题,可能在第一个文档中输入数据而第二个文档是空的,所以这种情况将被视为交易,如果是这样我应该如何避免我考虑改变注册过程,或者我应该考虑其他选项,如两阶段提交。
答案 0 :(得分:0)
如果您想确保&#39;用户&#39;之间的原子性。和学校&#39;集合,然后没有办法确保在MongoDB中,因为它不支持事务。您需要重新考虑您的mongo集合设计并将学校对象嵌入到用户对象中,因为MongoDB可确保文档级别的原子性。像这样:
{"userName":"xyz@abc.com","school":{"name":"xyz","city":"ny"}}
或MongoDB提供&#34;交易,如&#34;使用两阶段提交的语义: https://docs.mongodb.com/manual/tutorial/perform-two-phase-commits/