0

当用户尝试注册时,我的应用程序将他从表单输入的数据保存到两个不同的文档中

     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;


}

我的问题是,如果第一次写入和第二次写入之间出现问题,可能会在第一个文档中输入数据而第二个文档是空的,所以这种情况是否会被视为事务如果是这样我应该如何避免我正在考虑改变注册过程还是我应该考虑其他一些选项,例如两阶段提交。

4

1 回答 1

0

如果要确保“用户”和“学校”集合之间的原子性,那么在 MongoDB 中无法确保这一点,因为它不支持事务。您需要重新考虑您的 mongo 集合设计并将学校对象嵌入到您的用户对象中,因为 MongoDB 确保了文档级别的原子性。像这样的东西:

{"userName":"xyz@abc.com","school":{"name":"xyz","city":"ny"}}

或者 MongoDB 使用两个阶段提交提供“类似事务”的语义: https ://docs.mongodb.com/manual/tutorial/perform-two-phase-commits/

于 2017-04-11T17:15:46.673 回答