2017-04-11 45 views
0

我在我的應用程序時,用戶嘗試上申請他從表單中輸入的數據被保存到兩個不同的文件這是否被視爲mongodb中的事務?

 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

如果您想確保'用戶'和'學校'集合之間的原子性,那麼無法確保在MongoDB中,因爲它不支持事務。您需要重新考慮您的mongo集合設計,並將學校對象嵌入您的用戶對象中,因爲MongoDB確保文檔級別的原子性。事情是這樣的:

{"userName":"[email protected]","school":{"name":"xyz","city":"ny"}} 

或者MongoDB的使用提供了兩個相的語義「像交易」承諾: https://docs.mongodb.com/manual/tutorial/perform-two-phase-commits/

+0

,因爲用戶有不同的角色。用戶可以是一個老師或學生我我不能嵌入校對象正在考慮改變註冊頁面,所以起初我只獲取用戶集合相關數據,並在註冊後取決於角色獲取其他數據是否正確? – ashutosh